0

I am using WebRequest and WebReponse classes to get a response from a web api. The response I get is an xml of the following format

<?xml version="1.0" encoding="UTF-8"?>

<ROOT>
    <A></A>
    <B></B>
    <C></C>
    <D>
        <E NAME="aaa" EMAIL="[email protected]"/>
        <E NAME="bbb" EMAIL="[email protected]"/>
    </D>
</ROOT>

I want to get all the E elements as a List<E> or something.

Can some one guide me on this pls.

1

2 Answers 2

4

if you want to avoid serialization, as you only want a very specific part of the xml, you can do this with one LINQ statement:

var items = XDocument.Parse(xml)
              .Descendants("E")
              .Select(e => new 
                 {
                    Name = e.Attribute("NAME").Value, 
                    Email = e.Attribute("EMAIL").Value
                 })
              .ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

perfecto. Just to add to him I would prefer using .Descendants("D") .Descendants("E") so that if at all element E is added anywhere else in the xml output my code doesn't break. Thanks
0

Working example:

 var doc = XDocument.Parse(@"<?xml version='1.0' encoding='UTF-8'?>
<ROOT>
    <A></A>
    <B></B>
    <C></C>
    <D>
        <E NAME='aaa' EMAIL='[email protected]'/>
        <E NAME='bbb' EMAIL='[email protected]'/>
    </D>
</ROOT>");

            var elements = from el in doc.Elements()
                           from el2 in el.Elements()
                           from el3 in el2.Elements()
                           where el3.Name == "E"
                           select el3;
            foreach (var e in elements)
            {
                Console.WriteLine(e);
            }

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.