简体   繁体   中英

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.

<?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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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