【问题标题】:How to check if an element has two specific child?如何检查一个元素是否有两个特定的孩子?
【发布时间】:2022-01-15 02:34:49
【问题描述】:

如何使用 XML LINQ 进行检查?

我需要检查父母是否同时拥有 child1 和 child2。这应该返回 true:

<parent>
    <child1></child1>
    <child2></child2>
</parent>

这些都是假的:

<parent>
    <child1></child1>
</parent>

<parent>
    <child2></child2>
</parent>

【问题讨论】:

  • bool hasOneOrMoreOfBoth = xml.Elements("child1").Any() &amp;&amp; xml.Elements("child2").Any(); 限制为每次使用 1 次 .Count() == 1 而不是 .Any()

标签: c# xml linq


【解决方案1】:

假设您有一个包含 root 元素和 parent 元素集合的 XML 文件,例如:

<root>
    <parent>
        <child1></child1>
        <child2></child2>
    </parent>
    <parent>
        <child1></child1>
    </parent>
    <parent>
        <child2></child2>
    </parent>
</root>

您可以使用以下代码获取包含恰好一个child1 元素和恰好一个child2 元素的parents:

var xmlFile = @"[...Path to your xml file...]";

var root = XElement.Load(xmlFile);

var parents = root.Elements("parent");

var eligibleParents = parents
    .Where(p => p.Elements("child1").Count() == 1 
        && p.Elements("child2").Count() == 1);

parent 将包含:

<parent>
  <child1></child1>
  <child2></child2>
</parent>
<parent>
  <child1></child1>
</parent>
<parent>
  <child2></child2>
</parent>

eligibleParents 将包含:

<parent>
  <child1></child1>
  <child2></child2>
</parent>

表达式

p.Elements("child1").Count() == 1 
    && p.Elements("child2").Count() == 1

如果parent (p) 元素恰好有一个child1 和一个child2 子元素,则返回true。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    • 2011-07-01
    • 1970-01-01
    • 2018-08-07
    • 2012-07-29
    • 1970-01-01
    • 2023-04-05
    相关资源
    最近更新 更多