基于后代节点的属性选择节点的最佳LINQ-to-XML查询? [英] Best LINQ-to-XML query to select nodes based on properties of descendant nodes?

查看:63
本文介绍了基于后代节点的属性选择节点的最佳LINQ-to-XML查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下XML文档:

<?xml version="1.0" encoding="UTF-8"?>
<FamilyTree>
  <Parent name="Ken">
    <Child name="Lorna">
      <Grandchild name="Andrew"/>
      <Grandchild name="Brian"/>
    </Child>
    <Child name="Mike">
      <Grandchild name="Ann"/>
      <Grandchild name="Beth"/>
    </Child>
  </Parent>
  <Parent name="Norma">
    <Child name="Owen">
      <Grandchild name="Charles"/>
    </Child>
    <Child name="Peter">
      <Grandchild name="Charlotte"/>
    </Child>
  </Parent>
  <Parent name="Quinn">
    <Child name="Robert">
      <Grandchild name="Debbie"/>
      <Grandchild name="Eric"/>
    </Child>
    <Child name="Susan">
      <Grandchild name="Frank"/>
    </Child>
  </Parent>
  <Parent name="Tom">
    <Child name="Ursula">
      <Grandchild name="George"/>
      <Grandchild name="Harriet"/>
    </Child>
    <Child name="Victor">
      <Grandchild name="Ian"/>
      <Grandchild name="Juliet"/>
    </Child>
  </Parent>
</FamilyTree>

我正在尝试选择一个拥有至少两个自己的孩子(孙子")的孩子的父母".请注意,我不是在寻找至少有两个孙子"的父母".

I'm trying to select all the "Parents" with a Child who has at least two children ("Grandchild") of his/her own. Note that I'm not looking for "Parents" with at least two "Grandchild[ren]".

以下LINQ查询有效,但我感觉它不是最优雅的.

The following LINQ query works, but I've a feeling it's not the most elegant.

IEnumerable<XElement> parents = (from c in familyTreeElement.Descendants("Child")
                                 where c.Elements().Count() > 1
                                 select c.Parent).Distinct();

是否有更好的方法来指定呢?

Is there a better way to specify this?

推荐答案

啊(2个孙子)编辑帮助了;-p

Ahh the edit (2 grand-children) helps ;-p

虽然XDocument很有用,但有时我会想念XPath/XQuery.使用XmlDocument,您可以只使用doc.DocumentElement.SelectNodes("Parent[Child/Grandchild[2]]").

While XDocument is useful, at times I miss XPath/XQuery. With XmlDocument you could just use doc.DocumentElement.SelectNodes("Parent[Child/Grandchild[2]]").

这篇关于基于后代节点的属性选择节点的最佳LINQ-to-XML查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆