Current Node Path in XDocument

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

+4
source share
2 answers

Nothing is built in there, but you can 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 does not take into account the position of an element within its peer group.

+2
source

Depending on how you want to use XPath. In any case, you will need to go through the tree and build XPath along the way.

If you want to have a readable string for dispatching - just combining the names of the node nodes (see BrokenGlass suggestion) works fine

If you want to choose later in XPath

  • positional XPath (indicate the position of each node in its parent) is one option (something like // [3] / *). You should consider attributes as a special case, since there is no order defined for attributes
  • XPath with predefined prefixes (the namespace for the prefix must be stored separately) - / my: root / my: child [3] / o: prop1 / @ t: attr3
  • XPath with built-in namespaces when you want to get the received and portable XPath / * [name () = 'root' and namespace-uri () = 'http: //my.namespace'] / .... (see specification for name and uri namespace functions http://www.w3.org/TR/xpath/#function-namespace-uri )

Note that you must consider special nodes, such as comments and processing instructions, if you want a truly universal version of XPath for node inside XML.

+1
source

All Articles