How to Auto-Increment an Unique ID in XML Part III
After reading a bit about the XmlReader class, I recognized that it is much faster then other classes. This class provides you a fast non-cached stream access to the input. Furthermore you can read files that are larger than 2GB. The XmlTextReader and XmlValidatingReader do not provide this, there are limited and can only read files less than 2GB. I have changed my previous code according to this and looks now like this:
XML File:
<?xml version="1.0" encoding="ISO-8859-1"?>
<employee>
<person id="1">
<firstname>Bob</firstname>
<lastname>Jones</lastname>
<active>true</active>
</person>
<person id="5">
<firstname>Bob</firstname>
<lastname>Jones</lastname>
<active>true</active>
</person>
<person id="9">
<firstname>Bob</firstname>
<lastname>Jones</lastname>
<active>true</active>
</person>
<person id="15">
<firstname>Bob</firstname>
<lastname>Jones</lastname>
<active>false</active>
</person>
</employee>
Code:
private int GetNextNodeID()
{
// Read the xml file and lock it, so that somebody
// else is not able to use it.
FileStream file = new FileStream(Server.MapPath("test.xml"), FileMode.Open, FileAccess.ReadWrite, FileShare.None);
XmlTextReader reader = new XmlTextReader(file);
int nMaxID = 0;
while (reader.Read())
{
if (reader.IsStartElement() && reader.Name == "person")
{
int nID = Int32.Parse(reader.GetAttribute("id"));
if(nMaxID < nID) nMaxID = nID;
}
}
// Close the file. Now this file is again open for all.
file.Close();
nMaxID++;
return nMaxID;
}
This code is also available in the XML How To's section.
References: [msdn]
Sonu