Search code examples
c#xpathxpathnavigator

How to get all different element tags from root tag using XPath


I have a following xml file

<root>
  <element1>
    <header>header1</header>
    <tag1>tag1</tag1>
    <response>
      <status>success</status>
      <Data>
        <id>d1</id>
        <test>2</test>
      </Data>
      <Beta>
        <betaid>sdsd</betaid>
        <code>123</code>
        <code>ddd</code>
      </Beta>
    </response>
  </element1>
</root>

My Question: How to get the first child elements under "Response" tag? i.e staus, data and beta. Using XPath in C#. Thank you

The .net code i have is here but it does not work.

XPathDocument doc= new XPathDocument(XmlReaderdata);
XPathNavigator mes, Nav = doc.CreateNavigator();

foreach(XPathNavigator node in (XPathNodeIterator)Nav.Evaluate("//response/*)
{
            node.Name;
}

Solution

  • An XPath query like this should work:

    //response/*
    

    For example:

    var xml = @"<root> ... </root>";
    using (StringReader stream = new StringReader(xml))
    {
        XPathDocument doc= new XPathDocument(stream);
        XPathNavigator nav = doc.CreateNavigator();
        XPathNodeIterator itor = (XPathNodeIterator)nav.Evaluate("//response/*");
    
        foreach(XPathNavigator node in itor)
        {
            Console.WriteLine(node.Name);
        }
    }
    

    Produces the output:

    status
    Data
    Beta