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

 

Comments

# re: Retrieve XML Node Attributes In C#

Wednesday, March 12, 2008 3:18 PM by Funnynj

Hello HC,

Enjoy your site and code, simple, and to the point without having extra "junk" in it.

Works like a charm.

Thanks!

The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.