Domanda

I am trying to while loop on an XPathNodeIterator object

     XPathNodeIterator xpCategories = GetCategories().Current.Select("/root/category/id");    

now xpCategories holds an xml like this

 <root>
  <category numberofproducts="0">
    <id>format</id>
    <name>Kopi/Print</name>
  </category>
  <category numberofproducts="1">
    <id>frankering</id>
    <name>Kopi/Print</name>
  </category>
  <category numberofproducts="0">
    <id>gardbøjler</id>
    <name>Møbler</name>
  </category>
  <category numberofproducts="0">
    <id>gardknager</id>
    <name>Møbler</name>
  </category>
  <category numberofproducts="0">
    <id>gardspejle</id>
    <name>Møbler</name>
  </category>

</root>

And I need to get each of the category nodes "id" inside the loop.tried some thing like this

XPathNodeIterator xpCategories = GetCategories().Current.Select("/root/category/id");    
while (xpCategories.MoveNext())
Console.WriteLine(xpCategories.Current.Value);

But this loop works only one time after that it exits.I can't understand what is going wrong?

È stato utile?

Soluzione

It should be

while (xpCategories.MoveNext())
{
    XPathNavigator n = xpCategories.Current;
    Console.WriteLine(n.Value);
}

OR

foreach (XPathNavigator n in xpCategories)Console.WriteLine(n.Value);

Though I would recommend LINQ2XML

XDocument doc=XDocument.Load(xmlPath);
List<string> ids=doc.Elements("category")
                    .Select(x=>x.Element("id").Value)
                    .ToList();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top