2 回答

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超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貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超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 關(guān)注
- 234 瀏覽
添加回答
舉報(bào)