2009-06-03 120 views
3

我嘗試通過xml文檔進行循環,並且我仍然在第二次迭代中獲取第一個元素,不知道我缺少什麼。誰能幫忙?漂亮的新使用XPath使用xPath循環遍歷項目

string file = HttpContext.Current.Server.MapPath("~/XML/Locations.xml"); 

    Dictionary<string, Location> locationCollection = new Dictionary<string, Location>(); 

     XPathDocument xDocument = new XPathDocument(file); 
     XPathNavigator xPathNavigator = xDocument.CreateNavigator(); 

     foreach (XPathNavigator node in xPathNavigator.Select("//locations/*")) 
     { 
      string value = node.SelectSingleNode("/locations/location/cell").Value; 
     } 



    <?xml version="1.0" encoding="utf-8" ?> 
<locations> 
    <location> 
    <locationName>Glendale</locationName> 
    <street>3717 San Fernando Road</street> 
    <city>Glendale</city> 
    <state>CA</state> 
    <zipcode>91204</zipcode> 
    <generalManager>DJ Eldon</generalManager> 
    <phone>(818) 552‐6246</phone> 
    <tollFree>(888) 600‐6011</tollFree> 
    <fax>(818) 552‐6248</fax> 
    <cell>(347) 834‐2249</cell> 
    <counterEmail>[email protected]</counterEmail> 
    <directEmail>[email protected]</directEmail> 
    </location> 
    <location> 
    <locationName>Chicago</locationName> 
    <street>1301 S. Harlem Ave.</street> 
    <city>Chicago</city> 
    <state>IL</state> 
    <zipcode>60402</zipcode> 
    <generalManager>Dave Schnulle</generalManager> 
    <phone>(708) 749‐1500</phone> 
    <tollFree>(888) 966‐1500</tollFree> 
    <fax>(818) 552‐6248</fax> 
    <cell>(708) 749‐3800</cell> 
    <counterEmail>[email protected]</counterEmail> 
    <directEmail>[email protected]</directEmail> 
    </location> 
</locations> 

回答

11

你有效地忽略利用斜線,回到文檔根的node值。試試這個:

// This assumes that there are only location nodes under locations; 
// You may want to use //locations/location instead 
foreach (XPathNavigator node in xPathNavigator.Select("//locations/*")) 
{ 
    string value = node.SelectSingleNode("cell").Value; 
    // Use value 
} 

話雖如此,是否有任何理由你沒有在一個XPath查詢中做到這一點?

// Name changed to avoid scrolling :) 
foreach (XPathNavigator node in navigator.Select("//locations/location/cell")) 
{ 
    string value = node.Value; 
    // Use value 
} 
+0

謝謝,這工作得很好...是的,有一個原因,我沒有做一個單一的xpath,因爲我將添加multipule值到一個集合。 再次感謝! – BoredOfBinary 2009-06-03 16:06:36

0

嘗試以下操作:

XPathNodeIterator ni = xPathNavigator.Select("//locations/*"); 
while (ni.MoveNext()) 
{ 
    string value = ni.Current.Value); 
} 

只是一個快速的脫口而出,希望它可以幫助你。

0

你應該做的:

string value = node.SelectSingleNode("./cell").Value; 

當你做xPathNavigator.Select(「//位置/ *」)),你已經在/地點/位置,所以你需要一個元素下移節點,在你的例子中的單元格。