简体   繁体   English

如何计算包含特定元素的特定元素?

[英]How can I count specific elements that contain a specific element?

Considering xml like: 考虑像这样的xml:

<Main>
   <ActivityOne>
       <!-- this should be counted -->
       <TaskA>yes</TaskA>
       <TaskB>do do do</TaskB>
   </ActivityOne>
   <ActivityTwo>
       <ActivityFive>
           <TaskA>da da da</TaskA>
       </ActivityFive>
   </ActivityTwo>
       <ActivityOne>
           <!-- this should not be counted -->
           <TaskC>yadda yadda</TaskC>
       </ActivityOne>
   <ActivityThree>
       <ActivityOne>
           <!-- this should be counted -->
           <ActivityFour>
               <TaskA>yes</TaskA>
           </ActivityFour>
           <TaskC>nope</TaskC>
       </ActivityOne>
       <ActivityTwo>
           <TaskF>no</TaskF>
       </ActivityTwo>
   </ActivityThree>
   <ActivityFour>
       <TaskA>nope</TaskA>
   </ActivityFour>
</Main>

I am trying to count the number of "ActivityOne" elements that contain one or more "TaskA" elements anywhere within. 我试图计算包含任何一个或多个“ TaskA”元素的“ ActivityOne”元素的数量。

I tried this: 我尝试了这个:

int count = xDoc.Descendants("ActivityOne").Where(x => x.Descendants("TaskA").Count() > 0).Count();

But it only seems to count the ActivityOne elements that have a TaskA deeper than a direct child. 但这似乎只算出TaskA比直接子级更深的ActivityOne元素。

The solution you have provided is totally fine: 您提供的解决方案完全可以:

int count = xDoc.Descendants("ActivityOne")
                .Where(x => x.Descendants("TaskA").Count() > 0)
                .Count();

I would like to add one more solution which can help you to solve this problem using XPath: 我想再添加一个解决方案,它可以帮助您使用XPath解决此问题:

int count = xDoc.XPathSelectElements("//ActivityOne[descendant::TaskA]").Count();

It's a little bit shorter expression and, in my opinion, it's a better approach if you need to select some elements from XML using special conditions. 它的表达有点短,我认为,如果您需要使用特殊条件从XML中选择某些元素,那么这是一种更好的方法。

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

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