Suppose the following PowerShell line of code
$node = Select-Xml -Path $filePath -XPath "//*[@$someAttribute]"
How can I get the node's xpath? I figured I could just traverse up using its ParentNode property, but is there a better way to do it?
Suppose the following PowerShell line of code
$node = Select-Xml -Path $filePath -XPath "//*[@$someAttribute]"
How can I get the node's xpath? I figured I could just traverse up using its ParentNode property, but is there a better way to do it?
To extend Ansgar's answer slightly, the code can be made to find a partial Xpath that doesn't extend to the XML root. Only the child node and some definite attribute (a name in my code) of the "super-parent" (a parent at an unknown level) is required.
I don't think there's anything built into PowerShell to do what you want. Recursing upwards isn't too difficult, though. A function like this should work:
Ansgar Wiechers' helpful answer provides an elegant recursive function.
The following function builds on it while trying to remove some of its limitations:
It properly reflects a node's index among siblings of the same name so as to reliable target it; for instance, if the given node is an element named
foo
and there are two other, siblingfoo
elements that come before it, the returned path ends in.../foo[3]
It supports not just element nodes, but also attributes and text/CDATA nodes.
It avoids potential name collisions with the properties that PowerShell adds to provide direct, name-based access to the XML DOM, by using the
get_*()
methods to access type-native properties - see this answer for background information.Here's an example of its use:
The above yields: