Search code examples
c#xpathxml-parsingxpathnavigator

XPath for selecting a node under a specific node with zero or more nodes in between


My Xml looks something like this


      <root>
       <parent name="Iam">
          <child1 name="123">
              <toy name="wii">
              </toy>
          </child>
       </parent>
       <parent name="Iam">
          <toy name="wii">
          </toy>
       </parent>
       <parent name="Sam">
          <child1 name="999">
             <toy name="xbox">
             </toy>
           </child>
        </parent>
      </root>
   

I need to select all <toy> nodes with name="wii" under <parent> with name="Iam". Notice that <toy> can be direct child of <parent>or a grandchild of <parent>(under <child>)

<child>node can have 0 or more cardinality.

I tried using this xpath /parent[@name='Iam']/*/toy[@name='wii'] with XPathNavigator.

`XPathNodeIterator nodeIter = schemaNavigator.Select(schemaXPath, namespaceMgr);`

It is obviously wrong since it fails.

I need xpath for selecting all nodes between <parent> and <toy> with 0 or more cardinality.

I cannot change the format of XML.


Solution

  • This seemed to worked for me:

            string schemaXPath = "//parent[@name='Iam']//toy[@name='wii']";
            XPathNavigator schemaNavigator  = oXmlDocument.CreateNavigator();
            XPathNodeIterator nodeIter = schemaNavigator.Select(schemaXPath, namespaceMgr);
    
            while (nodeIter.MoveNext() == true)
            {
                Console.WriteLine(nodeIter.Current.Name);
            }
    

    Hopefully this is what you're looking for.

    Cheers!