0

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

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

但是这个循环在它退出后只工作一次。我不明白出了什么问题?

4

1 回答 1

1

它应该是

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

或者

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();
于 2013-10-10T06:35:15.450 回答