Search code examples
c#xmlchild-nodes

Select a subset of childnodes by name


Given this xml doc

<listOfItem>
  <Item id="1"> 
    <attribute1 type="foo"/>
    <attribute2 type="bar"/>
    <property type="x"/>
    <property type="y"/>
    <attribute3 type="z"/>
  </Item>
  <Item>
   //... same child nodes
  </Item>
 //.... other Items
</listOfItems>

Given this xml document, I would like to select, for each "Item" node, just the "property" child nodes. How can I do it in c# directly? With "directly" I mean without selecting all the child nodes of Item and then check one by one. So far:

XmlNodeList nodes = xmldoc.GetElementsByTagName("Item");
foreach(XmlNode node in nodes)
{
   doSomething()
   foreach(XmlNode child in node.ChildNodes)
   {
     if(child.Name == "property")
     {
        doSomethingElse()
     }
   }
}

Solution

  • You can use SelectNodes(xpath) method instead of ChildNodes property:

    foreach(XmlNode child in node.SelectNodes("property"))
    {
        doSomethingElse()
    }
    

    Demo.