How to read attribute value from XmlNode in C #?

Suppose I got an XmlNode and I want to assign the value of attirbute "Name". How can i do this?

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 Doc:

 <Root> <Employee Name ="TestName"> <Childs/> </Root> 
+79
c # xml
Oct 21 '09 at 10:50
source share
8 answers

Try the following:

 string employeeName = chldNode.Attributes["Name"].Value; 
+148
Oct 21 '09 at 10:54
source share

To extend Konamiman's solution (including all relevant null checks), this is what I did:

 if (node.Attributes != null) { var nameAttribute = node.Attributes["Name"]; if (nameAttribute != null) return nameAttribute.Value; throw new InvalidOperationException("Node 'Name' not found."); } 
+33
Jan 03 '13 at 1:55
source share

you can scroll through all the attributes as you do with nodes

 foreach (XmlNode item in node.ChildNodes) { // node stuff... foreach (XmlAttribute att in item.Attributes) { // attribute stuff } } 
+16
Oct 21 '09 at 10:54
source share

if all you need is names, use xpath instead. No need to iterate yourself and check for a null value.

 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"); 
+3
May 29 '15 at 8:22 pm
source share

Using

 item.Attributes["Name"].Value; 

gets value

+2
Oct 21 '09 at 10:55
source share

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

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

The return value will be an empty string if the attribute name does not exist.

So your loop might 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 the <node> surrounded by the <Node><N0de></N0de><Node> tags, and then scroll through them and read the Name attribute.

+2
May 19 '16 at 12:01
source share

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 exceptions when the expected attributeName does not actually exist.

+1
Mar 19 '17 at 13:57 on
source share

You can also use this:

 string employeeName = chldNode.Attributes().ElementAt(0).Name 
0
Apr 27 '16 at 12:06 on
source share



All Articles