<Root>
<P1 Text ="A" >
<P2 Text = "AA">
<P3 Text = "AAA">
<L Text = "l_A"/>
<L Text = "l_B"/>
<L Text = "l_C"/>
</P3>
<P3 Text = "BBB">
<L Text = "l_D"/>
<L Text = "l_E"/>
<L Text = "l_F"/>
</P3>
</P2>
<P2 Text = "BB">
<L Text = "l_G"/>
<L Text = "l_H"/>
<L Text = "l_I"/>
</P2>
</P1>
</Root>
从一个包含数千个最多 10 层深的可变嵌套节点的 XML 文档,我 想以编程方式仅检索属于任何“P” parent 的叶子 如下:例如,在上面的示例中,选择 P2“AA”会将 l_A 转换为 l_F,而选择 P3“BBB”会将 l_D 转换为 l_F。
最佳答案
像这样(返回字符串列表):
XDocument doc = XDocument.Load(@"test.xml");
string level = "P3";
string levelAttr = "AAA";
var list = (from d in doc.Descendants(level)
let xAttribute = d.Attribute("Text")
where xAttribute != null && xAttribute.Value == levelAttr
from l in d.Descendants("L")
let lAttribute = l.Attribute("Text")
where lAttribute != null
select lAttribute.Value);
如果 Text
属性始终存在,您可以删除属性空检查...
关于c# - 在 XML 文档中使用 C# 从不同分支的父节点检索叶子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11328668/