user2729272
user2729272

Reputation: 359

how to select a parent node having a specific child node?

Here is my XML,

<A>
    <B id = "1">
        <R>
        <C id="ABC" />
    </B>
    <B id = "2" >
        <R>
        <C id="ABC" />
    </B>
    <B id = "3" >
        <R>
        <C id="XYZ" />
    </B>
    <B id = "4">
        <R>
    </B>
    <B id = "5">
        <R>
    </B>
 </A>

I Need to select only <B> nodes that contains child element <C> and output should be like,

<B id = "1">
        <R>
        <C id="ABC" />
</B>
<B id = "2" >
        <R>
        <C id="ABC" />
</B>
<B id = "3" >
        <R>
        <C id="XYZ" />
</B> 

Descendants("B").Descendants("C") is not helping.

Any help appreciated!

Upvotes: 0

Views: 774

Answers (2)

Andrei V
Andrei V

Reputation: 7508

XElement xml = XElement.Parse("xmlData");//or load...
var bElements = xml.Descendants("B").Where(x => x.Descendants("C").Count() > 0);

Alternatively, as suggested by Selman22, you ca use:

var bElements = xml.Descendants("B").Where(x => x.Descendants("C").Any());

Upvotes: 4

w.b
w.b

Reputation: 11238

XElement element = XElement.Parse("data.xml");
var query = element.Descendants("C")
            .Where(c => c.Parent.Name == "B")
            .Select(c => c.Parent).Distinct()
            .ToList();

Upvotes: 1

Related Questions