How to Auto-Increment an Unique ID in XML
In some cases you will need to create unique ID's for each node in your xml file. For example just think of something like an employee xml file. Let say your xml file looks like this (In the xml example, I assume that there will be always a person id.).
<?xml version="1.0" encoding="ISO-8859-1"?>
<employee>
<person id="1">
<firstname>Bob</firstname>
<lastname>Jones</lastname>
</person>
<person id="2">
<firstname>Bob</firstname>
<lastname>Jones</lastname>
</person>
</employee>
And now you would like to create a function which returns the next ID for the person, which should be 3 in our case. For that purpose I wrote a small function which reads the total nodes and incremenets it with one. The function looks like this:
private int GetNextNodeID()
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("employee.xml"));
XmlNodeList nodes = doc.SelectNodes("//employee/person");
int nNodeID = nodes.Count;
nNodeID++;
return nNodeID;
}
Sonu