How to convert xml string to an object using c#

648 views Asked by At

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.

2

There are 2 answers

1
Jonesopolis On BEST ANSWER

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();
0
Viktor Kireev On

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