【问题标题】:Linq to XML casting XML file to custom objectLinq to XML 将 XML 文件转换为自定义对象
【发布时间】:2015-09-15 13:20:58
【问题描述】:

我正在使用 Linq to XML 读取 XML 文件,作为其中的一部分,我想创建一个对象。我的对象如下所示:

    public class Address
    {
        public string AccountRef { get; set; }
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        // more stuff here
    }

我的 XML 文件如下所示:

<rows>
    <row>
      <FIELD NAME="AccountRef">1234</FIELD>
      <FIELD NAME="AddressLine1">My Address Line 1</FIELD>
      <FIELD NAME="AddressLine2">My Address Line 2</FIELD>
    </row>
    <row>
      <FIELD NAME="AccountRef">5678</FIELD>
      <FIELD NAME="AddressLine1">My Address Line 3</FIELD>
      <FIELD NAME="AddressLine2">My Address Line 4</FIELD>
    </row>
</rows>

在代码方面,我尝试了各种方法,但目前我有以下以格式返回正确的行数:

<row><FIELD NAME="AccountRef">1234</FIELD><FIELD>...rest of data</row>
<row><FIELD NAME="AccountRef">5678</FIELD><FIELD>...rest of data</row>

执行此操作的代码是:

var results = (from d in document.Descendants("row")
               select d).ToList();

所以基本上我想做的是:

var results = (from d in document.Descendants("row")
               select new Address
               {
                   AccountRef = d.Attribute("AccountRef").Value,
                   AddressLine1 = d.Attribute("AddressLine1").Value
               }).ToList();

显然因为我的节点是相同的(FIELD NAME)无法工作,所以有人知道我如何实现这一点吗?

【问题讨论】:

    标签: c# xml linq


    【解决方案1】:

    您需要在创建对象之前检索字段名称和值

    var results = document.Descendants("row")
        .Select(row=>row.Elements("FIELD").ToDictionary(x=>x.Attribute("NAME").Value, x=>x.Value))
        .Select(d=>new Address 
           {                    
            AccountRef = d["AccountRef"],
            AddressLine1 = d["AddressLine1"],
            AddressLine2 = d["AddressLine2"],
           });
    

    查看demo

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 2018-05-08
      • 1970-01-01
      • 1970-01-01
      • 2010-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多