XPathNodeIterator上的while循环问题

时间:2013-10-10 06:32:23

标签: c# asp.net xpath xpathnodeiterator

我正在尝试在XPathNodeIterator对象上进行while循环

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

现在xpCategories拥有像这样的xml

 <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>

我需要在循环中获取每个类别节点“id”。这样的事情

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

但是这个循环在它退出后只运行一次。我无法理解出了什么问题?

1 个答案:

答案 0 :(得分:1)

应该是

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

OR

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

虽然我推荐LINQ2XML

XDocument doc=XDocument.Load(xmlPath);
List<string> ids=doc.Elements("category")
                    .Select(x=>x.Element("id").Value)
                    .ToList();