简体   繁体   English

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

[英]C# LINQ with XML, cannot extract multiple fields with same name into object

Trying to read into an object the following XML file (can be changed) into a VAR using LINQ XML. 尝试使用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>

What isn't working is reading multiple elements into the object. 不起作用的是将多个元素读入对象。 I can only read the first one. 我只能看第一个。 Obviously the Object that holds the field needs to be an array? 显然,保存字段的对象必须是数组吗? This is the code I have so far. 这是我到目前为止的代码。

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();
     }
 }
}

Thanks in advance. 提前致谢。

Use the Elements method to get all of the field elements, then call Select to turn them into objects. 使用Elements方法获取所有field元素,然后调用Select将其变成对象。

For example: 例如:

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()
    };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM