我有一些这样的代码:
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();
}
}
是否可以定义一个字符串数组或其他一些我可以用来声明这些字典对象的数据结构?这是一些愚蠢的伪代码帮助展示我的想法:
编辑下面伪代码中的变量 fieldNames 将是我期望的名称数组,而不是基于 xml 源字段名称。我将忽略 xml 源中未在 fieldNames 数组中明确设置的任何字段名称。
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}
}
};