【发布时间】:2018-11-05 01:51:25
【问题描述】:
请注意,每个<Field></Field> 可以有不同的元素,例如突出显示的<I32> 或<String>。我想在这样的数据网格视图中显示元素名称,其中类型是元素的名称(I32 或字符串或<Field> 的其他子元素):-
到目前为止,我已经尝试过这段代码,但它返回 An unhandled exception of type 'System.NullReferenceException'。
XDocument doc = XDocument.Load("GetLotDetails.xml");
var data = doc.Descendants("Document").Where(x => (String)x.Attribute("name") == "DATA").SelectMany(x => x.Elements("Field"));
var query = from d in data
let str = d.Element("String").Name
let other = d.Element("I32").Name
select new
{
Name = d.Attribute("name").Value,
Type = str.Equals("String") ? "String" : (other.Equals("I32") ? "I32" : null),
Value = d.Value,
};
dataGridView1.DataSource = query.ToList();
所以想法是让匿名Type = *whatever element name under field*。如何在 LINQ select 语句中提取不同的元素名称并将其赋予相同的未知类型变量?
【问题讨论】: