Home > Mobile >  How to check if an element has two specific child?
How to check if an element has two specific child?

Time:12-10

How to check this with XML LINQ?

I need to check if parent has child1 and child2 both. This should return true:

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

These are false:

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

or

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

CodePudding user response:

Assuming you have an XML file with a root element and a collection of parent elements, such as:

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

You can get the parents containing both exactly one child1 element and exactly one child2 element by using the following code:

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 would contain:

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

eligibleParents would contain:

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

The expression

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

returns true if the parent (p) element has exactly one child1 and exactly one child2 children element.

  • Related