XDocument 中当前节点的路径

Dou*_*oug 6 c# linq-to-xml

是否可以在 XDocument 中获取当前 XElement 的路径?例如,如果我遍历文档中的节点,是否有某种方法可以获得该节点(XElement)的路径,以便它返回类似 \root\item\child\currentnode 的内容?

Bro*_*ass 3

没有内置任何内容,但您可以编写自己的扩展方法:

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();
Run Code Online (Sandbox Code Playgroud)

但这并没有考虑元素在其对等组中的位置。