简体   繁体   English

如何计算已读入字符串的XML节点

[英]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. 我已经将XML文件读入字符串strSiteList。 Here's a shortened sample of the XML: 这是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): 您可以使用简单的XPath表达式(需要使用“ System.Xml.XPath”):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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