gpt4 book ai didi

c# - 使用 xPath 遍历项目

转载 作者:行者123 更新时间:2023-11-30 13:29:27 26 4
gpt4 key购买 nike

我正在尝试遍历 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com