How to read attribute value from XmlNode in C#?

Ashish Ashu picture Ashish Ashu · Oct 21, 2009 · Viewed 273.5k times · Source

Suppose I have a XmlNode and I want to get the value of an attribute named "Name". How can I do that?

XmlTextReader reader = new XmlTextReader(path);

XmlDocument doc = new XmlDocument();
XmlNode node = doc.ReadNode(reader);

foreach (XmlNode chldNode in node.ChildNodes)
{
     **//Read the attribute Name**
     if (chldNode.Name == Employee)
     {                    
         if (chldNode.HasChildNodes)
         {
             foreach (XmlNode item in node.ChildNodes)
             { 

             }
         }
      }
}

XML Document:

<Root>
    <Employee Name ="TestName">
    <Childs/>
</Root>

Answer

Konamiman picture Konamiman · Oct 21, 2009

Try this:

string employeeName = chldNode.Attributes["Name"].Value;

Edit: As pointed out in the comments, this will throw an exception if the attribute doesn't exist. The safe way is:

var attribute = node.Attributes["Name"];
if (attribute != null){
    string employeeName = attribute.Value;
    // Process the value here
}