How to Auto-Increment an Unique ID in XML Part II
After the great suggestions which I received in How to Auto-Increment an Unique ID in XML, I re-designed the code according to the suggestions. The current code will now also work with ID's that are not sequential and it will find the highest ID. If you are going to work with the code and xml, then I would recommend that you do not delete any elements, because this will create duplicate ID's. Instead you should set the active element to false. Here is the new 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>
And here is the new function:
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);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
XmlNodeList nodes = xmlDoc.SelectNodes("/employee/person");
int nMaxID = 0;
for(int i=0;i<nodes.Count;i++)
{
if(nMaxID < Int32.Parse(nodes[i].Attributes["id"].Value))
nMaxID = Int32.Parse(nodes[i].Attributes["id"].Value);
}
// Close the file. Now this file is again open for all.
file.Close();
nMaxID++;
return nMaxID;
}
Fire up your feedback ;)
Sonu
Note: This function is much slower when you work with many nodes.