【发布时间】:2011-10-19 02:18:54
【问题描述】:
我正在尝试从 xml 文件中读取“数据”元素中的所有属性并将它们显示在 DataGrid(WPF、.Net 4.0)中
XML 格式如下所示。
<root>
<Data Name1="Value1" Name2="Value2" ... />
<Data Name1="Value1" Name2="Value2" ... />
...
</root>
我不知道使用的属性名称(例如 Name1、Name2、Foo 等)或每个元素中的属性数量(每个元素的属性数量可能不同)。每个新元素都应显示在新行上,每个属性对应一列(如果该行不存在则显示 null)。
我正在努力为要绑定的数据网格创建一个支持类,或者以编程方式创建它。
我目前的尝试是创建一组文本列(根据我从 xml 文件中提取的内容给出要使用的列名列表)
List<string> dataTags = ...; //get list of attributes to use from xml
foreach (string d in dataTags) {
DataGridTextColumn col = new DataGridTextColumn();
col.Header = d;
dataGrid.Columns.Add(col);
}
然后,如果属性名称与标题值之一匹配,我将遍历每个属性并将其添加到列表中(以表示要在数据网格中显示的行)
foreach (XElement e in xml.Descendants("Data")) {
//Store values to be added to the datagrid as a new row
List<string> row = new List<string>();
//Only add data where the attribute name matches one of the 'dataTags' we are given.
foreach(string d in dataTags) {
foreach (XAttribute a in e.Attributes()) {
if (d.Equals(a.Name.ToString())) {
row.Add(a.Value);
break;
}
}
}
//Add new row to the datagrid
dgData.Items.Add(row);
}
我在那儿有点……但是有一个带有空白行的数据网格(行数正确,但现在显示了数据)。
任何提示/指针将不胜感激。
【问题讨论】: