3

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.

1 Answer 1

8

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()
    };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.