select elements with the name attribute name in special xml structure

user1154138 picture user1154138 · Jan 17, 2012 · Viewed 18.5k times · Source

below is the structure of my xml document. I just want to first take the value of every node <attribute name="a"> then make a comparison of it with a given value. However I don't how to locate <attribute name="a"> of each node using xml selectnodes in c#. Google searches don't show any working solutions.

<nodes>     
 <node name = "node1">      
  <attribute name="a">This is node1 a</attribute>
  <attribute name="b">This is node1 b</attribute>
 </node>
 <node name = "node2">      
  <attribute name="a">This is node2 a</attribute>
  <attribute name="b">This is node2 b</attribute>
 </node>
 ...
</nodes>     

Answer

Digbyswift picture Digbyswift · Jan 17, 2012

You could use Linq to XML, something like the following:

string xml = "<nodes>...";

var results = from node in XDocument.Parse(xml).Descendants()
          where node.Name == "attribute"
          select node.Value;

You could then loop through the results as required.

There is a nice Linq to XML overview here too.