I have an XML doc like this:
<Persons>
<Person Id="10000" FullName="Jon Doe">
<Status StatusID="1" StatusDesc="Active"/>
<Fields>
<Field FieldId="1" Value="xxxx"/>
<Field FieldId="2" Value="yyyy"/>
<Field FieldId="2" Value="zzzz"/>
</Fields>
</Person>
<Person Id="10001" FullName="John Smith">
<Status StatusID="2" StatusDesc="New"/>
<Fields>
<Field FieldId="3" Value="aaaa"/>
<Field FieldId="4" Value="bbbb"/>
<Field FieldId="5" Value="ccccv"/>
</Fields>
</Person>
</Persons>
I want to write an XML query that returns the “Person” ID and all “Fields” elements.
I can get all “Fields” elements but not the “Person” ID.
The same applies when I need the “Status” element.
Any help will be appreciated.
Try something like this:
This will give you a sequence of anonymous types that look something like this:
The reason that I used the
Descendantsmethod to retrieve the fields is because the element I am first working with is thePersonelement. SinceElementsonly returns nodes that are direct children it would not work to retrieve the fields so I usedDescendantsinstead.To enumerate the results you can do this: