1

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?

3
  • Your reason for not using Parent isn't clear at all. Could you give an example of why it might fail? Commented Nov 15, 2010 at 13:35
  • @Jon: It sounds like he's saying that the nesting may be different. Commented Nov 15, 2010 at 13:38
  • @SLaks: It's possible, but not clear... and not clear what he wants to do if that's the case. Commented Nov 15, 2010 at 13:40

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks SLacks, this is what I was looking for. For the other guys, the problem is that in the future I may have the Person element nested into 4 or 5 more parents so that the PersonList element may be the 5th parent element and not anymore the 3rd like now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.