简体   繁体   中英

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM