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' ]
Hey Hemant, we can use the double dot (“..”) to access the parent of any node using the XPath. For example – The locator //span[@id=”first”]/.. will return the parent of the span element matching id value as 'first.
For the div element with an id attribute of hero //div[@id='hero'] , these XPath expression will select elements as follows: //div[@id='hero']/* will select all of its children elements. //div[@id='hero']/img will select all of its children img elements.
As defined in the W3 XPath 1.0 Spec, " child::node() selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.
For the first query use:
//role[@key = 'add-user']/ancestor::*
For the second:
//role[@key = 'security-admin']//*
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