Path of Current Node in XDocument
Asked Answered
D

3

6

Is it possible to get the path of the current XElement in an XDocument? For example, if I'm iterating over the nodes in a document is there some way I can get the path of that node (XElement) so that it returns something like \root\item\child\currentnode ?

Dauntless answered 5/5, 2011 at 20:54 Comment(1)
Take a look at the code at this linkHoltz
E
4

There's nothing built in, but you could write your own extension method:

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();

This doesn't account for the position of the element within its peer group though.

Erwinery answered 5/5, 2011 at 21:8 Comment(0)
A
2

I know the question is old, but in case someone wants to get a simple one liner:

XElement element = GetXElement();
var xpath = string.Join ("/", element.AncestorsAndSelf().Reverse().Select(a => a.Name.LocalName).ToArray());

Usings:

using System.Linq;
using System.Xml.Linq;
Anapest answered 18/5, 2021 at 11:46 Comment(0)
T
1

Depending on how you want to use the XPath. In either case you'll need to walk tree up yourself and build XPath on the way.

If you want to have readable string for dispaly - just joining names of prent nodes (see BrokenGlass suggestion) works fine

If you want select later on the XPath

  • positional XPath (specify position of each node in its parent) is one option (something like //[3]/*). You need to consider attributes as special case as there is no order defined on attributes
  • XPath with pre-defined prefixes (namespace to prefix need to be stored separately) - /my:root/my:child[3]/o:prop1/@t:attr3
  • XPath with inlined namespaces when you want semi-readable and portable XPath /*[name()='root' & namespace-uri()='http://my.namespace']/.... (see specification for name and namespace-uri functions http://www.w3.org/TR/xpath/#function-namespace-uri)

Note that special nodes like comments and processing instructions may need to be taken into account if you want truly generic version of the XPath to a node inside XML.

Tranquilize answered 5/5, 2011 at 23:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.