我有一些像这样的代码:
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}
}
};
答案 0 :(得分:5)
使用Enumerable.ToDictionary
:
var report1 =
from report in doc.Root.Elements("Report1").Elements("Row")
select new[] {"Field1", "Field2", "Field3"}
.ToDictionary(x => x, x => report.Elements(x).First().Value)
答案 1 :(得分:2)
伪代码实际上非常接近你真正可以做的事情。我假设你已经准备好了一个单独的fieldNames集合。
IEnumerable<string> fieldNames = ...;
XDocument doc = ...;
var report1 = doc.Root.Elements("Report1").Elements("Row")
.Select(report =>
{
var d = new Dictionary<string, string>();
foreach (var fieldName in fieldNames)
{
d.Add(fieldName, report.Elements(fieldName).First().Value);
}
return d;
});
答案 2 :(得分:1)
不要尝试在单个集合初始化程序中执行所有操作。
对于这样的事情,我会创建一个单独的方法:
public static Dictionary<string, string> MapReport(XElement report)
{
var output = new Dictionary<string, string>();
foreach(var field in report.Elements())
{
output.Add(field.Name, ...);
}
}
然后查询会更简单:
var report1 = from report in doc.Root.Elements("Report1").Elements("Row")
select MapReport(report)
答案 3 :(得分:1)
这将为您提供类型List<Dictionary<string,string>>
var rows = doc.Descendants("Row")
.Select(r => r.Elements()
.ToDictionary(x => x.Name.LocalName, x => x.Value))
.ToList();
...
var data = rows[i]["Field1"];