使用xPath循环遍历项目

时间:2009-06-03 15:47:52

标签: c# asp.net xpath

我正在尝试遍历xml文档,我仍然在第二次迭代中获得第一个元素,不知道我缺少什么。有人可以帮忙吗?相当新的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>BUR@Eaglerider.com</counterEmail>
    <directEmail>DJ@Eaglerider.com</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>ORD@Eaglerider.com</counterEmail>
    <directEmail>Dave@Eaglerider.com</directEmail>
  </location>  
</locations>

3 个答案:

答案 0 :(得分:12)

通过使用前导斜杠返回文档根目录,您实际上忽略了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
}

答案 1 :(得分:0)

尝试以下方法:

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

快速脱口而出,希望它可以帮到你。

答案 2 :(得分:0)

你应该这样做:

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

当您执行xPathNavigator.Select(“// locations / *”))时,您已经位于/ locations / location内,因此您需要在示例中的节点,单元格中仅移动一个元素。

相关问题