C# LINQ with XML, cannot extract multiple fields with same name into object
c#, linq, object, xml
Solution
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()
};
Problem
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>(?<ssn>\d{3}-\d{2}-\d{4})</Regex> </linebegins> <regex>"(?<last>\s{0,1}[A-Z-'.]+\s{0,1}[A-Z-'.]+),(?<first>\s[A-Z-'.]+\s{0,1})(?<middle>[A-Z][.]|\s{0,1})"></Regex> <regex>"(?<ssn>\d{3}-\d{2}-\d{4})"</Regex> <regex>"(?<total>\$[,/d]+)(?<adjust>\$[,/d]+)(?<monthly>\$[,/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.