使用 Linq To XML,获取所有叶子路径的方法? [英] Using Linq To XML, method to get path to all leaves?
问题描述
好的,我有以下 XML 树
Ok, I've got the following XML tree
<root>
<A>
<A1>
<A1A>1000</A1A>
<A1B>2000</A1B>
<A1C>3000</A1C>
</A1>
<A2>
<A2A>4000</A2A>
<A2B>5000</A2B>
</A2>
</A>
<B>
<B1>
<B1A>6000</B1A>
</B1>
</B>
</root>
从接收 XDocument 的方法中,我想生成一个字典,其中键是路径(实际上是 XPath),值来自相应叶中的值.
From a method receiving an XDocument I want to produce a dictionary where the key is the path (really an XPath) and the value comes from the value in the corresponding leaf.
root/A/A1/A1A 1000
root/A/A1/A1B 2000
root/A/A1/A1C 3000
root/A/A2/A2A 4000
root/A/A2/A2B 5000
root/B/B1/B1A 6000
在 Linq to XML 中做起来似乎很简单,但我无法理解它.
Seems simple to do in Linq to XML but I can't wrap my head around it.
推荐答案
您可以通过查找没有后代的元素来找到叶子:
You can find the leaves by looking for elements that have no descendants:
var doc = XDocument.Load(fileName);
var leaves =
from e in doc.Descendants()
where !e.Elements().Any()
select e;
我不知道有没有内置的方法来获取元素的路径,但是你可以很容易地创建一个扩展方法来构建它:
I don't know if there is a built-in way to get the path of an element, but you can easily create an extension method to build it:
static class Extensions
{
public static string Path(this XElement element)
{
XElement tmp = element;
string path = string.Empty;
while (tmp != null)
{
path = "/" + tmp.Name + path;
tmp = tmp.Parent;
}
return path;
}
}
然后你可以像这样构建字典:
You can then build the dictionary like this:
var dict = leaves.ToDictionary(e => e.Path(), e => e.Value);
这篇关于使用 Linq To XML,获取所有叶子路径的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!