Tuesday, September 30, 2008

Reading attributes value of an Xml node

It is common to read the attribute of an xml node while trying to read xml files. Lets we have an xml like below -


We can write the following code to read the value of the attribute “id” of the first customer –

// Load the xml file
XmlDocument doc = new XmlDocument();
doc.LoadXml(Resources.XMLFile);

// Read the first customer element
XmlNode customer = doc.DocumentElement.SelectSingleNode("customer");

// Initialize the reader using the customer node
// from where need to read attributes
XmlNodeReader reader = new XmlNodeReader(customer);
reader.Read();

// Read the attribute named - "id"
string id = reader.GetAttribute("id");
Console.WriteLine(id);

The output of this program is "123". I find it helpful during working one of my project and I think it will also help you. You can also read this value very easily if you use LINQ in C# 3.0.