James B
James B

Reputation: 9595

Using linq to find parent with attribute

I have the following XML

<Configuration>
    <Organisation Count="2">        
        <ID>1234</ID>    
        <UKPRN Count = "2">
            <NAME>
                <FIRST>abcd</FIRST>
                <LAST>efgh</LAST>   
            </NAME>     
        </UKPRN>            
    </Organisation>
</Configuration>

I've tried this

var test = root.Elements().Where(p => p.Attribute("Count") != null).Select(p => p.Descendants("FIRST"));

but that's the wrong way round. Can't quite get my head around how to get hold of the parent.

How do I use linq to identify the closest parent element with the attribute Count, e.g. element FIRST should return UKPRN and element ID should return Organisation?

Upvotes: 1

Views: 422

Answers (1)

DavidG
DavidG

Reputation: 118947

You can use the Ancestors() method to get all the parents and choose the first one that has the attribute you require:

var pairs = root.Descendants()
    .Select(e => new 
    {
        Element = e, 
        CountElement = e.Ancestors().FirstOrDefault(a => a.Attribute("Count") != null) 
    });

Upvotes: 2

Related Questions