Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xpath to select all parents and all children

Tags:

xml

xslt

xpath

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>
  1. I want to select all parents of the element with key 'add-user' .the result would be:

    [ 'users-admin' , 'security-admin' , 'total-admin' ]
    
  2. I want to select all children of 'security-admin'. the result would be:

    [ 'users-admin' , 'add-user' , 'delete-user' , 'deactivate-user' ]
    
like image 804
javad helali Avatar asked Mar 06 '13 05:03

javad helali


People also ask

How does XPath select parent?

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.

How do you find the child element in XPath?

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.

What is child :: In XPath?

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.


1 Answers

For the first query use:

//role[@key = 'add-user']/ancestor::*

For the second:

//role[@key = 'security-admin']//*
like image 176
Kirill Polishchuk Avatar answered Sep 20 '22 22:09

Kirill Polishchuk