是否可以在 XDocument 中获取当前 XElement 的路径?例如,如果我遍历文档中的节点,是否有某种方法可以获得该节点 (XElement) 的路径,以便它返回类似\root\item\child\currentnode 的内容?
最佳答案
没有内置任何东西,但您可以编写自己的扩展方法:
public static string GetPath(this XElement node)
{
string path = node.Name.ToString();
XElement currentNode = node;
while (currentNode.Parent != null)
{
currentNode = currentNode.Parent;
path = currentNode.Name.ToString() + @"\" + path;
}
return path;
}
XElement node = ..
string path = node.GetPath();
但这并没有考虑元素在其对等组中的位置。
关于c# - XDocument中当前节点的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5903953/