【发布时间】:2018-12-13 18:07:55
【问题描述】:
我有一个 xml 文件,我尝试从特定节点检索数据。但是有些节点丢失了,所以我想返回空字符串。下面是我的代码示例,我正在使用 LINQ。
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
where el.Element("name").Value.Equals("Val1")
select el.Value).ToList();
Details 对象包含 2 个员工节点及其子节点,因此我想根据名称节点值获取子节点值。此外,我想为丢失的节点返回空字符串(例如位置节点第一部分中缺少,但在第二部分中存在)
提前致谢。
【问题讨论】:
标签: c# linq-to-xml