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 ?
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.
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.
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.
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:
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With