【问题标题】:Parse XML string to List/DataTable in C#在 C# 中将 XML 字符串解析为 List/DataTable
【发布时间】:2020-12-23 09:42:36
【问题描述】:

我有一个XML string 下面给出了两列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 string 转换为list,我尝试使用下面的LINQ expression 转换为Parse

LINQ - 表达式

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

错误 -

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

在结果集中,我期望两列都有各自的值。我是否必须使用datatablelist 以外的任何其他名称。

请帮忙! TIA

【问题讨论】:

    标签: c# xml linq parsing datatable


    【解决方案1】:

    实际上 包含值,你必须添加到你的 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();
    

    【讨论】:

    • 但它没有指定的列名用于进一步处理数据。
    • 是的,成功了!但是如何始终按Active = -1 对结果集进行排序。即Active = -1 的记录应该比0 的其他记录高
    • 你可以在 ToList() 之后添加 .OrderBy(x => x.Active)
    • 当我尝试访问元素值时不起作用,可能是因为var?
    • OrderBy(x => x.Active) before ToList()?
    【解决方案2】:

    你只会下降一层然后尝试解析所有子元素

    <RECORD COL_HEADER="0">
      <no> 201738 </no>
      <Active> -1 </Active>
    </RECORD>
    

    转换成一个整数。你需要把它们单独拿出来,像这样

    List<Record> records = XElement.Parse(xmlString)
        .Descendants("RECORD")
        .Select(x => new Record((int)x.Element("no"), (int)x.Element("Active")))
        .ToList();
    
    
    public class Record
    {
        public readonly int No;
        public readonly int Active;
    
        public Record(int no, int active)
        {
            this.No = no;
            this.Active = active;
        }
    }
    

    【讨论】:

    • 没有Record 类我就不能了吗?
    • 当然可以!你几乎可以随心所欲地操纵它。 Karmin 刚刚编辑了他的答案,展示了如何使用匿名类型。您希望它在列表中后的外观如何,我将相应地编辑我的答案
    【解决方案3】:

    我更喜欢使用这种方式而不是使用Descendants

    var result = XDocument.Parse(xmlString).Root?               // => RECORDS 
        .Elements()                                             // => RECORD
        .Select(c => new {
            no =  int.Parse(c.Element("no")?.Value ?? "0"), 
            active = c.Element("Active")?.Value == "-1"})
        .ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-03
      • 1970-01-01
      • 2015-11-23
      • 1970-01-01
      • 2019-02-02
      • 1970-01-01
      • 2022-11-15
      相关资源
      最近更新 更多