Reputation: 270
I need to write 2 xpath queries one of which selects all parents of a specific element from the element's direct parent to the root and then I will be able to select some specific attribute of the elements.
and the other selects all children of an element no matter where they are.
for example if the xml document is something like :
<role key='total-admin'>
<role key='security-admin'>
<role key='users-admin'>
<role key='add-user'></role>
<role key='delete-user'></role>
<role key='deactivate-user'></role>
</role>
</role>
</role>
I want to select all parents of the element with key 'add-user' .the result would be:
[ 'users-admin' , 'security-admin' , 'total-admin' ]
I want to select all children of 'security-admin'. the result would be:
[ 'users-admin' , 'add-user' , 'delete-user' , 'deactivate-user' ]
Upvotes: 7
Views: 9535
Reputation: 197832
You always have a context node that you define as being an element with a specific attribute value, e.g. "add-user"
or "security-admin"
:
//*[@key = "string"]
As this gives you a nodeset the expression for the context node needs to exclude all non-single elements of such a kind:
//*[@key = "string" and count(//*[@key = "string"]) = 1]
This solves the needs for your context node. You can then represent that contextnode with either the .
or write it in there verbatim.
Select all parents, grandparents, grand-grandparents and so on of the context element (that is the ancestor axis):
./ancestor::*
//*[@key = "string" and count(//*[@key = "string"]) = 1]/ancestor::*
Select all children (that is the descendant axis):
./descendant::*
.//*
//*[@key = "string" and count(//*[@key = "string"]) = 1]/descendant::*
//*[@key = "string" and count(//*[@key = "string"]) = 1]//*
Upvotes: 3
Reputation: 56172
For the first query use:
//role[@key = 'add-user']/ancestor::*
For the second:
//role[@key = 'security-admin']//*
Upvotes: 10