Hi I have the following X开发者_运维知识库ML 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?
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;
精彩评论