Pergunta

I have an XPathNodeIterator named _xpCategories which holds a data like this

        <root>
      <category numberofproducts="0">
        <id>hoved</id>
        <url>/products/hovednavigation</url>
        <name>HOVEDNAVIGATION</name>
        <category numberofproducts="0">
          <id>embalfors</id>
          <url>/products/emballage-og-forsendelse</url>
          <name>Emballage og forsendelse</name>
          <category numberofproducts="0">
            <id>gaveindpak</id>
            <url>/products/gaveindpakning</url>
            <name>Gaveindpakning</name>
            <category numberofproducts="3">
              <id>cellofan</id>
              <url>/products/cellofan</url>
              <name>Cellofan</name>
            </category>
            <category numberofproducts="30">
              <id>gavebånd</id>
              <url>/products/gavebaand</url>
              <name>Gavebånd</name>
            </category>
          </category>
          <category numberofproducts="0">
            <id>kuvkonv</id>
            <url>/products/kuverter-og-konvolutter</url>
            <name>Kuverter og konvolutter</name>
          </category>
          </category>
      </category>
</root>

I want to traverse through each categories in this xml and print id of each one. I had done some code like this.

 while (_xpCategories.MoveNext())
    {
        Console.WriteLine(_xpCategories.Current.SelectSingleNode("id"));

    }

But this loop only works one ,only first category id is getting,then it exist the loop.Can any one point out what I am doing wrong?

Foi útil?

Solução

you need to modify your XPath expression to select all the categories within your document no matter where they are within the document, as you have 1 parent category with child categories and then child categories within those child categories.

/root/category - this will just select the parent category node (1 node) with many child nodes.

//category - this should select all categories within the XML document no matter where they appear.

take a look here and here for more help

Outras dicas

You can use an XPathNavigator with XPathNodeIterator like this

(A modified example from here)

XPathDocument document = new XPathDocument("yourxml.xml");
XPathNavigator navigator = document.CreateNavigator();

XPathNodeIterator _xpCategories = navigator.Select("//category");
_xpCategories.MoveNext();

while (nodesText.MoveNext())
    Console.WriteLine(nodesText.Current.Value);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top