开发者

How to count nodes in XML that have been read into a string

I'm sure the solution is pretty trivial to the experienced, but it's not to me. I have read an XML file into a开发者_开发技巧 string, strSiteList. Here's a shortened sample of the XML:

<siteList>
  <site code="s0000001">
    <nameEn>Edmonton</nameEn>
    <provinceCode>AB</provinceCode>
  </site>
  <site code="s0000002">
    <nameEn>Vancouver</nameEn>
    <provinceCode>BC</provinceCode>
  </site>
</siteList>

How do I count the number of times a site appears? I've started with this:

XDocument loaded = XDocument.Parse(strSiteList);
int sitesCount = loaded.Nodes().Count(d => "some code that should work...arg...";

But I am lost as to whether it's the right way to start this or not.

Thanks!


A particular site? That sounds to me like:

string site = "s0000002";
XDocument loaded = XDocument.Parse(xml);
int sitesCount = loaded.Descendants("site")
                       .Count(x => (string) x.Attribute("code") == site);

For all sites, just:

int sitesCount = loaded.Descendants("site").Count();


You can use simple XPath expression (using "System.Xml.XPath" required):

XDocument loaded = XDocument.Parse(xml);
int sitesCount = loaded.XPathSelectElements("siteList/site").Count();


Assuming that it's been read in correctly, you should be able to do this:

int sitesCount = loaded.Descendants("site").Where(x => x.Attribute("code").Value == "1234").Count();

You can also do this:

int sitesCount = loaded.Descendants("site").Count(x => x.Attribute("code").Value == "1234");

If you're looking for a count of all the sites, you can just do this:

int sitesCount = loaded.Descendants("site").Count();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜