我正在尝试循环遍历 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>[email protected] /cdn-cgi/l/email-protection</counterEmail>
<directEmail>[email protected] /cdn-cgi/l/email-protection</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] /cdn-cgi/l/email-protection</counterEmail>
<directEmail>[email protected] /cdn-cgi/l/email-protection</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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)