Ashish Ashu
Ashish Ashu

Reputation: 14667

How to read attribute value from XmlNode in C#?

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>

Upvotes: 142

Views: 328795

Answers (9)

Spencer Sullivan
Spencer Sullivan

Reputation: 575

Expanding on Konamiman's solution above. I needed to loop through multiple attributes for a node.

Telecom theTelecom = new Telecom();
if (node.HasAttributes)
{
     var nameAttributeList = node.Attributes();
     foreach (XAttribute a in nameAttributeList)
     {
         if ((null != a.Name?.LocalName) && 
               ("use" == a.Name.LocalName))
         {
             theTelecom.use = a.Value;
         }
         if ((null != a.Name?.LocalName) && 
               ("value" == a.Name.LocalName))
         {
             theTelecom.value = a.Value;
         }
     }
}

Upvotes: 0

Konamiman
Konamiman

Reputation: 50273

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
}

Upvotes: 244

rahul
rahul

Reputation: 187030

Use

item.Attributes["Name"].Value;

to get the value.

Upvotes: 3

TaW
TaW

Reputation: 54433

Yet another solution:

string s = "??"; // or whatever

if (chldNode.Attributes.Cast<XmlAttribute>()
                       .Select(x => x.Value)
                       .Contains(attributeName))   
   s =  xe.Attributes[attributeName].Value;

It also avoids the exception when the expected attribute attributeName actually doesn't exist.

Upvotes: 1

Marco7757
Marco7757

Reputation: 764

If you use chldNode as XmlElement instead of XmlNode, you can use

var attributeValue = chldNode.GetAttribute("Name");

The return value will just be an empty string, in case the attribute name does not exist.

So your loop could look like this:

XmlDocument document = new XmlDocument();
var nodes = document.SelectNodes("//Node/N0de/node");

foreach (XmlElement node in nodes)
{
    var attributeValue = node.GetAttribute("Name");
}

This will select all nodes <node> surrounded by <Node><N0de></N0de><Node> tags and subsequently loop through them and read the attribute "Name".

Upvotes: 7

cell-in
cell-in

Reputation: 789

You can also use this;

string employeeName = chldNode.Attributes().ElementAt(0).Name

Upvotes: 1

an phu
an phu

Reputation: 1823

if all you need is the names, use xpath instead. No need to do the iteration yourself and check for null.

string xml = @"
<root>
    <Employee name=""an"" />
    <Employee name=""nobyd"" />
    <Employee/>
</root>
";

var doc = new XmlDocument();

//doc.Load(path);
doc.LoadXml(xml);

var names = doc.SelectNodes("//Employee/@name");

Upvotes: 4

Ari Roth
Ari Roth

Reputation: 5534

To expand Konamiman's solution (including all relevant null checks), this is what I've been doing:

if (node.Attributes != null)
{
   var nameAttribute = node.Attributes["Name"];
   if (nameAttribute != null) 
      return nameAttribute.Value;

   throw new InvalidOperationException("Node 'Name' not found.");
}

Upvotes: 46

balexandre
balexandre

Reputation: 75073

you can loop through all attributes like you do with nodes

foreach (XmlNode item in node.ChildNodes)
{ 
    // node stuff...

    foreach (XmlAttribute att in item.Attributes)
    {
        // attribute stuff
    }
}

Upvotes: 17

Related Questions