如何在c#中将XML解析为通用列表

问题描述 投票:0回答:1

我正在调用Web API并获取XmlResult所以我想读取这个XML结果并转换为Generic List。

这是我的xml格式

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

我解码我的XML并删除XML的第一个节点,我可以捕获我的纯XML,但现在当我尝试填充列表时,我无法访问Elements("row")

为什么?有什么想法吗?

在这里我的代码

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();
}
c# xml asp.net-web-api
1个回答
1
投票

a)您不使用xml命名空间

b)Tip和Total是属性,而不是元素

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();
© www.soinside.com 2019 - 2024. All rights reserved.