I have some code like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
class Program
{
static void Main(string[] args)
{
string xml = @"<Root>
<Report1>
<Row>
<Field1>data1-1</Field1>
<Field2>data1-2</Field2>
<!-- many more fields -->
</Row>
<Row>
<Field1>data2-1</Field1>
<Field2>data2-2</Field2>
<!-- many more fields -->
</Row>
</Report1>
</Root>";
XDocument doc = XDocument.Parse(xml);
var report1 = from report in doc.Root.Elements("Report1").Elements("Row")
select new Dictionary<string, string>()
{
{"Field1", report.Elements("Field1").First().Value},
{"Field2", report.Elements("Field2").First().Value}
};
var i = 1;
foreach (Dictionary<string, string> dict in report1)
{
Console.WriteLine(String.Format("Row{0}: ", i));
Console.WriteLine(" Field1: {0}", dict["Field1"]);
Console.WriteLine(" Field2: {0}", dict["Field2"]);
i++;
}
Console.ReadLine();
}
}
Would it be possible to define a string array or some other data structure that I could use to declare these dictionary objects? Here is some silly pseudo code help show my idea:
EDIT The variable fieldNames in the pseudo code below would be an array of names I expect, not based on the xml source field names. I will be ignoring any field names within the xml source that are not explicitly set in the fieldNames array.
var report1 = from report in doc.Root.Elements("Report1").Elements("Row")
select new Dictionary<string, string>()
{
foreach (var fieldName in fieldNames)
{
{fieldName, report.Elements(fieldName).First().Value}
}
};