Raffaeu
Raffaeu

Reputation: 7003

LinQ to XML; query descendants using parent node value

Hi I have the following XML structure:

<Root>
 <Persons>
  <PersonList Category="Employee">
   <Person Name="John" Id="5" />
   <Person Name="Mary" Id="10" />
  </PersonList>
 </Persons>
</Root>

I am looking to use LinqtoXML and in order to get a list of available Person I can simply write this query:

var persons = from p in myDoc.Descendants("Person")
select p;

Now, what I have to do in order to get all the Person where the Category in PersonList Element is = to a specific value? I can't use Parent because I need to specify the PersonList element as the structure of the XML may be different than this one but not the element name. Is it possible?

Upvotes: 1

Views: 2170

Answers (1)

SLaks
SLaks

Reputation: 888195

It sounds like you're looking for

var people = myDoc.Descendants("PersonList")
                  .Where(p => p.Attribute("Category").Value == something)
                  .Descendants("Person");

If you want to get the category of a specific <Person> element, you can write

var category = elem.AncestorsAndSelf("PersonList")
                   .First().Attribute("Category").Value;

Upvotes: 2

Related Questions