Search code examples
c#asp.netxml-serializationjsonserializer

How to convert xml string to an object using c#


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.


Solution

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