首页 > 解决方案 > 在 C# 中将 XML 字符串解析为 List/DataTable

问题描述

我在XML string下面给出了 2 列noActive

XML -

<RECORDS RECORDCOUNT="2">
    <RECORD COL_HEADER="0">
        <no>201738</no>
        <Active>-1</Active>
    </RECORD>
    <RECORD COL_HEADER="0">
        <no>201739</no>
        <Active>0</Active>
    </RECORD>
</RECORDS>

并将上述内容转换XML stringlist我尝试Parse使用以下内容LINQ expression

LINQ - 表达式

var result = XElement.Parse(xmlString)
                    .Descendants().Where(r => !string.IsNullOrEmpty(r.Value))
                    .Select(r => int.Parse(r.Value))
                    .ToList();

错误 -

输入字符串的格式不正确。

在结果集中,我期望两列都有各自的值。我是否必须使用datatable或除list.

请帮忙!TIA

标签: c#xmllinqparsingdatatable

解决方案


实际上 <RECORD COL_HEADER="0"> 包含值,你必须添加到你的 Where 一个额外的检查是这样的

Where(r => !string.IsNullOrEmpty(r.Value) && (r.Name == "no" || r.Name == "Active"))

为了获得您的期望,您可以尝试以下操作:

var result = XElement.Parse(xmlString)
.Descendants().
Where(x => x.Name == "RECORD")
.Select(x => new
{
    no = int.Parse(x.Element("no").Value),
    Active = int.Parse(x.Element("Active").Value)
}
).ToList();

推荐阅读