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="a@a.com"/>
        <E NAME="bbb" EMAIL="b@b.com"/>
    </D>
</ROOT>

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

Can some one guide me on this pls.

Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
  • Have class for xml and use XmlSerialization Deserialize method to convert xml to object of that newly created class- http://msdn.microsoft.com/en-us/library/dsh84875%28v=vs.110%29.aspx – malkam Nov 24 '14 at 13:40

2 Answers2

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();
Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
  • 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 – Yasser Shaikh Nov 25 '14 at 05:25
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='a@a.com'/>
        <E NAME='bbb' EMAIL='b@b.com'/>
    </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);
            }
Viktor Kireev
  • 1,200
  • 1
  • 8
  • 17