Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Path of Current Node in XDocument

Tags:

c#

linq-to-xml

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 ?

like image 747
Doug Avatar asked May 05 '11 20:05

Doug


People also ask

How to get the path of current script using Node JS?

How to get the path of current script using Node.js ? We can get the path of the present script in node.js by using __dirname and __filename module scope variables. __dirname: It returns the directory name of the current module in which the current script is located.

How to use XPath syntax in xdocument?

Let's read the file first and get the XDocument object to use XPath syntax. Let's start with XPath syntax one by one to select nodes based on your requirement. Select all Courses and trainings nodes using '//' symbol for all elements. //select all Courses Node irrespective of where it is defined.

What are nodes in XPath?

In XPath, there are seven kinds of nodes: element, attribute, text, namespace, processing-instruction, comment, and document nodes. XML documents are treated as trees of nodes. The topmost element of the tree is called the root element. Atomic values are nodes with no children or parent.

What are nodes in an XML document?

In XPath, there are seven kinds of nodes: element, attribute, text, namespace, processing-instruction, comment, and document nodes. XML documents are treated as trees of nodes. The topmost element of the tree is called the root element. Look at the following XML document: Example of nodes in the XML document above:


2 Answers

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.

like image 151
BrokenGlass Avatar answered Sep 29 '22 09:09

BrokenGlass


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;
like image 45
donatasj87 Avatar answered Sep 29 '22 07:09

donatasj87