2 回答
TA贡献1784条经验 获得超7个赞
这是您的工作示例。你可以从这里
string xml = @"<root>
<employee>
<name>Val1</name>
<age>30</age>
</employee>
<employee>
<name>Val1</name>
<age>30</age>
<position>Priest</position>
</employee>
</root>";
XElement x = XElement.Parse(xml);
IEnumerable<XElement> details = x.Elements();
var valLst = (from el in details
let pos = (el.Element("position") == null ? string.Empty : el.Element("position").Value)
where el.Element("name").Value.Equals("Val1")
select new {n = el.Value, p = pos}).ToList();
Console.WriteLine(valLst[0].n + " - " + valLst[0].p);
Console.WriteLine(valLst[1].n + " - " + valLst[1].p);
输出:
Val130 -
Val130Priest - 牧师
TA贡献1875条经验 获得超3个赞
这会给你一个IEnumerable<AnonymousType>
var valLst =(from el in details
select new
{
Name = el.Element("name").Value,
Position = el.Element("position")?.Value ?? ""
});
输出:
"{ Name = Val1, Position = }"
"{ Name = Val1, Position = Priest }"`
- 2 回答
- 0 关注
- 194 浏览
添加回答
举报