2013-10-10 23 views
0

我想while循環創建XPathNodeIterator對象問題與同時創建XPathNodeIterator

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

現在xpCategories持有這樣

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

一個XML的,我需要得到每個類別的節點「id」在loop.tried這樣的一些事情是這樣的

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

但是這個循環只工作一次之後它退出了。我不明白髮生了什麼問題?

回答

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(); 
+0

我想你的第一個和第二個方法,我已經解釋過同樣的問題在這個問題上依然存在。並且隨着我的進取來自第三方API的XML我不能使用Document doc = XDocument.Load(xmlPath); 。(將沒有路徑給予) – Athul

+0

@AKS你嘗試過'// category/id' – Anirudha