【问题标题】:How to count child XElements in where clause如何在 where 子句中计算子 XElements
【发布时间】:2011-02-17 13:34:22
【问题描述】:
<Automobiles>
  <Cars>
    <YearofMfr></YearofMfr>
    <Mileage></Mileage>
    <MeterReading></MeterReading>
    <Color></Color>
    <Condition></Condition>
  </Cars>
  <Cars>
    <YearofMfr></YearofMfr>
    <Color></Color>
    <Condition></Condition>
  </Cars>
</Automobiles>

如何获得包含所有子元素的元素。要详细解释。我有上面的xml。从这里我想检索具有所有子节点的单个节点。如果您在第二个节点中看到一些信息丢失。我试过这样做。

var nodes = from nodeElements in doc.Descendants().FirstOrDefault().Elements()
                 where doc.Descendants().Count()==5
                select nodeElements;

我需要一个具有 5 个子元素的节点作为输出。

<Cars>     
<YearofMfr></YearofMfr>     
<Mileage></Mileage>     
<MeterReading></MeterReading>     
<Color></Color>     
<Condition></Condition>   
</Cars>

【问题讨论】:

  • 很难理解你想要什么。你能添加一些xml并描述你需要的输出吗?
  • 首选doc.Root而不是doc.Descendants().FirstOrDefault()
  • 此查询已解决。但仍然为有类似问题的人改写了我的问题。

标签: xml linq linq-to-xml xelement


【解决方案1】:

我建议您改为从 nodeElements.Descendants 中选择您的计数:

var nodes = (from nodeElements in doc.Root.Elements()
            where nodeElements.Descendants().Count()==5
            select nodeElements).FirstOrDefault();

更新以反映下面的评论和对您原始问题的评论。

【讨论】:

  • 非常感谢您的超快响应。丹尼尔的反应奏效了。 StackOverFlow 摇滚!!!
  • 如果我使用 XDocument 作为源对象(即 doc),上面的例子工作正常。但如果我使用 XElement,它会返回 null。抱歉又给您添麻烦了……
  • 我在这里添加了一个关于“查找重复的 xelements”的问题。 stackoverflow.com/questions/5076772/find-duplicate-xelements。 @daniel-hilgarth 请帮忙。
  • 我猜查询 XDocument 和 XElement 之间存在差异。当我使用 XDocument 作为源时,以下查询有效。 var nodes = (from nodeElements in doc.Root.Elements() where nodeElements.Descendants().Count()==5 select nodeElements).FirstOrDefault();当我将源更改为 XElement 时。我不得不更改为 IEnumerable nodes = (from nodeElements in payLoad.DescendantsAndSelf().Elements() where nodeElements.Descendants().Count() == 5 select nodeElements);这里 abv 2 查询的主要区别是 doc.Root.Elements() 和 payLoad.DescendantsAndSelf().Elements()。
猜你喜欢
  • 2011-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多