saulyasar
saulyasar

Reputation: 815

How to parse XML to Generic List in c#

I'm calling WebAPI and getting an XmlResult so I want to read this XML result and convert to Generic List.

Here my xml format

<SalesList xmlns="http://schemas.microsoft.com/2003/10/Serialization/"><row Total="103700.0000" Tip="Dry"/><row Total="9341.0000" Tip="Wet"/></SalesList>

I decode my XML and delete first node of XML and I can catch my pure XML but now when I try to fill list I cannot reach Elements("row")

Why? Have any idea?

Here my code

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8095/ ");


client.DefaultRequestHeaders.Accept.Add(
    new MediaTypeWithQualityHeaderValue("application/xml"));


string link = "api/Values/GeneralReport";

var response = client.GetAsync(link).Result;
string res = "";
using (HttpContent content = response.Content)
{
    Task<string> result = content.ReadAsStringAsync();
    res = result.Result;
}
XDocument doc = XDocument.Parse(res);
XElement firstChild = doc.Root.Elements().First();
string res1 = firstChild.ToString();
XDocument doc1 = XDocument.Parse(res1);
if (doc1.Root != null)
{
    var  listxml = (from r in doc1.Root.Elements("row")
                    select new StationInfo{
                     ItemType = (string)r.Element("Tip"),
                     Total = (decimal)r.Element("Total")}).ToList();
}

Upvotes: 0

Views: 370

Answers (1)

Eser
Eser

Reputation: 12546

a) You don't use the xml namespace

b) Tip and Total are attributes, not elements

XNamespace ns = "http://schemas.microsoft.com/2003/10/Serialization/";
var listxml  = XDocument.Parse(res)
                .Descendants(ns + "row")
                .Select(x => new
                {
                    ItemType = (string)x.Attribute("Tip"),
                    Total = (string)x.Attribute("Total"),
                })
                .ToList();

Upvotes: 1

Related Questions