C# LINQ with XML,无法将同名的多个字段提取到对象中

标签 c# xml linq object

尝试使用 LINQ XML 将以下 XML 文件(可以更改)读入对象到 VAR。

<?xml version='1.0'?>
<config>
    <report>
        <name>Adjustment Report</name>
        <extension>pdf</extension>
        <filetype>adobe_pdf</Filetype>
        <field name="total" type="currency" />
        <field name="adjust" type="currency" />
        <field name="monthly" type="currency" />
        <output>
            <format>Excel</format>
            <AutoFormat>True</AutoFormat>
        </output>
        <reportstart>adjustment report</reportstart>
        <reportend></reportend>
        <linebegins>
            <regex>(?&lt;ssn&gt;\d{3}-\d{2}-\d{4})</Regex>
        </linebegins>
        <regex>"(?&lt;last&gt;\s{0,1}[A-Z-'.]+\s{0,1}[A-Z-'.]+),(?&lt;first&gt;\s[A-Z-'.]+\s{0,1})(?&lt;middle&gt;[A-Z][.]|\s{0,1})"></Regex>
        <regex>"(?&lt;ssn&gt;\d{3}-\d{2}-\d{4})"</Regex>
        <regex>"(?&lt;total&gt;\$[,/d]+)(?&lt;adjust&gt;\$[,/d]+)(?&lt;monthly&gt;\$[,/d]+)"</Regex>
    </report>
</config>

不起作用的是将多个元素读入对象。我只能读第一本。显然持有字段的对象需要是一个数组?这是我目前的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ElementDemo
{
 class Program
 {
  static void Main(string[] args)
  {

   XElement xml = XElement.Load("C:\\TEMP\\test.xml");

   var reports = from report in xml.Descendants("report")
    where report.Element("name").Value.Contains("Adjustment Report")
    select new
    {
    Name = report.Element("name").Value,
    Extension = report.Element("extension").Value,
    FileType = report.Element("filetype").Value,
    // Fields : How is this done?
   };

   foreach(var obj in reports)
   {
    Console.WriteLine("Name: " + obj.Name );
   };
   Console.ReadLine();
     }
 }
}

提前致谢。

最佳答案

使用 Elements方法获取所有 field 元素,然后调用 Select将它们变成对象。

例如:

var reports = from report in xml.Descendants("report")
    where report.Element("name").Value.Contains("Adjustment Report")
    select new {
        Name = report.Element("name").Value,
        Extension = report.Element("extension").Value,
        FileType = report.Element("filetype").Value,
        Fields = report.Elements("field")
            .Select(f => new {
                Name = f.Attribute("name").Value, 
                Type = f.Attribute("type").Value 
            }).ToArray()
    };

关于C# LINQ with XML,无法将同名的多个字段提取到对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1980263/

相关文章:

c# - 如何使这两种方法更有效

c# - 在 Starcounter 中启用 CORS

c# - PFX ConcurrentQueue - 有没有办法从队列中删除特定项目

javascript - 谷歌控制台 Node 中的站点地图 xml

xml - 可以将用户数据存储在 XML 文件中吗?

c# - 获取列表中大于所选项目的项目

c# - CS0019 无法将 Vector2 与 double 相乘

c# - 仅从指定的命名空间解决依赖关系

xml - XSD 架构 : How to specify the number of digits in a value?

c# - 访问成员表达式的值