Reputation: 264
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 ?
Upvotes: 6
Views: 5196
Reputation: 900
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;
Upvotes: 2
Reputation: 100545
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
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.
Upvotes: 1
Reputation: 160942
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.
Upvotes: 4