0

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

2
  • 1
    I think you should replace your OrderBy by GroupBy(x => x.FirstNode.Value) Commented May 22, 2016 at 12:32
  • I've just realized I used orderby there :) I changed it to groupby but it still does not work. it says (operator == cannot be applied to operands of type method group and string) Commented May 22, 2016 at 12:37

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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();

Comments

1

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();

Comments

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.