Retrieve XML Node Attributes In C#
In this blog post, I will show you how to navigate the XML file and get all a list of nodes in order to access their attributes.
Text.xml
Below is a XML file used in this example
<?xml version="1.0" encoding="utf-8" ?>
<Document>
<List id="1"></List>
<List id="2"></List>
<List id="3"></List>
<List id="4"></List>
<List id="5"></List>
<List id="6"></List>
<List id="7"></List>
</Document>
C# Code
// Create a instance of XmlDocument Object
XmlDocument mydoc = new XmlDocument();
// Get the XML file path
string xmlFilePath = Server.MapPath("~") + "/text.xml";
// Load the XML File
mydoc.Load(xmlFilePath);
// Use the SelectNodes method to get a nodelist of the specified XPATH
XmlNodeList nodelist = mydoc.SelectNodes("Document/List");
// Loop through the nodelist
for(int i=0;i<nodelist.Count;i++)
{
// Set for each element in the nodelist to XmlNode
XmlNode node = nodelist[i];
// Get the node's attributes
XmlAttributeCollection attCol = node.Attributes;
// Print them for testing
Response.Write(attCol[0].Value + "<br/>");
}
Do not forget to import System.Xml namespace. The above code is commented to help you out understanding the steps taken
using System.Xml;
Best Regards,
HC