Yavuz Yavuz - 24 days ago 11
ASP.NET (C#) Question

Getting Values From XML With Linq Query

I have below XML file.

<Root>
<r1>
<n1>Person1</n1>
<n2>Type1</n2>
</r1>
<r1>
<n1>Person1</n1>
<n2>Type2</n2>
</r1>
<r1>
<n1>Person2</n1>
<n2>Type2</n2>
</r1>
<r1>
<n1>Person2</n1>
<n2>Type3</n2>
</r1>
<r1>
<n1>Person2</n1>
<n2>Type4</n2>
</r1>
<r1>
<n1>Person2</n1>
<n2>Type4</n2>
</r1>
</Root>


What I want is to get Types based on Persons. For example I tried below query expecting Type1 and Type2 values for person1 but it did not work.

XDocument doc = XDocument.Parse(XML_Document);

XElement[] pages = doc
.Descendants("r1")
.OrderBy(x => x.FirstNode.Value=="person1")
.ToArray();


Which query I should use to get it? Or is there a better way to deal with XML documents in asp.net C#?

Answer

You can use Where() to filter r1 by n1 child element value, and then use Select() to return the corresponding n2 element value :

string[] types = doc.Descendants("r1")
                     .Where(x => (string)x.Element("n1") == "person1")
                     .Select(x => (string)x.Element("n2"))
                     .ToArray();

And add Distinct() after Select() if you want to explicitly remove duplicate values.

Comments