c# - 使用 xPath 遍历项目

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

最佳答案

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

关于c# - 使用 xPath 遍历项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/945512/

相关文章:

c# - 无法将 Int 类型转换为 List

asp.net - 如何使用 jQuery 和 asp.net 进行 onclientclick 回发

尝试匹配另一个元素的同级元素之后的 XSLT 错误

c# - 达到错误最大池大小?

c# - 在 JetBrains PyCharm 上使用 IronPython

c# - 使用股票报价数据构建基于时间的条形图

c# - 在 ASP.NET 页面或母版页中注册 .ascx ASP.NET 用户控件是否会加载?

asp.net - 处理丢失的 AssociatedControlID 的好方法

python - Scrapy:为每个start_url动态生成规则

ruby - 无法使用 ruby​​ 中的 Mechanize 缩小 xpath 以提取表