Yavuz
Yavuz

Reputation: 1393

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#?

Upvotes: 0

Views: 75

Answers (3)

Maddy
Maddy

Reputation: 774

Try using where statement like below which would give you two xelements

        XElement[] pages = doc.Descendants("r1")
                              .Where(x => x.Element("n1").Value == "Person1")
                              .ToArray();

Upvotes: 2

har07
har07

Reputation: 89285

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.

Upvotes: 2

Krasimir Krastev
Krasimir Krastev

Reputation: 71

Try to use the following code:

var pages = doc.
            Descendants("r1").
            Where(r1 => r1.Element("n1").Value == "person1").
            Select(r1 => r1.Element("n2").Value).
            ToArray();

Upvotes: 1

Related Questions