c# – 使用xPath循环遍历项目

c# – 使用xPath循环遍历项目,第1张

概述我试着循环一个xml文档,我仍然在第二次迭代中得到第一个元素,不知道我错过了什么.有人可以帮忙吗? Xpath很新 string file = HttpContext.Current.Server.MapPath("~/XML/Locations.xml"); Dictionary<string, Location> locationCollection = new Dictionary 我试着循环一个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>
解决方法 您通过使用前导斜杠返回到文档根目录,实际上忽略了节点的值.试试这个:

// This assumes that there are only location nodes under locations;// You may want to use //locations/location insteadforeach (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循环遍历项目全部内容,希望文章能够帮你解决c# – 使用xPath循环遍历项目所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1221320.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存