Question:
I am trying to find a formula that creates a URL for an element based on its position in the XML hierarchy.
This is my sample xml:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
I have a function in Powershell that recursively iterates down from the top and on each ‘Content’ element I want to generate a concatenation of the ancestors Url values.
So it should generate consecutively for each ‘Content’ Node:
1 2 3 4 5 |
http://mysite.abc http://mysite.abc/sub1 http://mysite.abc/sub1/sub2 http://mysite.abc/sub1/sub2/sub3 |
I use at the moment as a start:
( $Node = the ‘Content’ element )
1 2 |
$Sites = $Node | Select-XML -XPath "//ancestor::Site" |
But for every $Node it selects all the ‘Site’ elements.
It would expect it to find more ancestors while going down in the xml structure.
If someone would know how to concatenate the values directly with Xpath that would be especially great, but for starters, I would be happy to know what is going wrong with my current approach.
Answer:
//ancestor::Site
will give you the ancestral Site
node relative to any node (//
) in the tree.
Use ./ancestor::Site
to grab only the ancestor relative to the current node (.
):
1 2 |
$Sites = $Node | Select-XML -XPath "./ancestor::Site" |