Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent node from XPATH descendant value

I have a HTML structure that I am attempting to test using XPATH. The structure I'll looking at currently is something like:

<div id="item_1" class="item-wrapper">
    <div class="container item">

        <div class="container-header">
            <h2 id="title">test-title</h2>
            <h5 id="description">test-description</h5>
        </div>

    </div>
</div>

There are a number of 'items' in my document, each with a unique ID. Using XPATH I want to 'get' the item_1 node from the value of the title id node ("test-title" in this case).

I also want to do this in such a way that is not dependant on the node tag (div/h2/etc).

I've been playing around with predicates, but I can't seem to get a solution that works. For example:

//*[@class="item-wrapper"][./*[@id="title"][text()="test-title"]] 

Thanks for any help!

like image 911
olan Avatar asked Oct 01 '13 14:10

olan


People also ask

How can I get parent node in XPath?

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 I get descendant in XPath?

Xpath Descendant is defined as a context node that is represented by the descendant axis; a descendant is a child node, a child of a child, and so on; consequently, the descendant axis doesn't contain attribute or namespace nodes. XPath is a mini-language that describes a node pattern to select a set of nodes.

What does descendant mean in XPath?

The descendant axis indicates all of the children of the context node, and all of their children, and so forth. Attribute and namespace nodes are not included - the parent of an attribute node is an element node, but attribute nodes are not the children of their parents.


1 Answers

You can use the below XPATH :

 //*[@id="title"]/ancestor::*[@id="item_1"][1]

Or, you can also use the function Function: node-set id(object)

 id('title')//ancestor::*[@id="item_1"][1]

Update

 //*[.="test-title"]/ancestor::*[@class="item-wrapper"][1]

output

<div id="item_1" class="item-wrapper">
    <div class="container item">

        <div class="container-header">
            <h2 id="title">test-title</h2>
            <h5 id="description">test-description</h5>
        </div>

    </div>
</div>
like image 100
Arup Rakshit Avatar answered Sep 29 '22 04:09

Arup Rakshit