9
<div>
    <dt>
        Test 1
    </dt>
    <dd>
    </dd>
    <dt>
        Test 2
    </dt>
    <dd>
    </dd>
</div>

I have this XPath written so far

//dt[contains(text(), "Test")]/self::dt|following-sibling::dd

But this is not bringing both dt and dd but just dt.

5 Answers 5

5

If it must be a single XPath 1.0 expression then you'll have to say

//dt[contains(., 'Test')] | //dt[contains(., 'Test')]/following-sibling::dd[1]

The final [1] is important, as without that it would extract all dd elements that follow a dt containing "Test", i.e. given

<div>
    <dt>
        Test 1
    </dt>
    <dd>
        Foo
    </dd>
    <dt>
        Something else 2
    </dt>
    <dd>
        Bar
    </dd>
</div>

the version without the [1] would match three nodes, the dt containing "Test 1" and both the "Foo" and "Bar" dd elements. With the [1] you would correctly get only "Test 1" and "Foo".

But depending on exactly how you're using the XPath it may be clearer to first select

//dt[contains(., 'Test')]

and then iterate over the nodes that this matches, and evaluate

. | following-sibling::dd[1]

in the context of each of those nodes in turn.

4

When using XPath 2.0:

//dt[contains(text(), "Test")]/(self::dt, following-sibling::dd)
1
  • 1
    that's very neat. but I am using 1.0
    – Umair A.
    Commented May 16, 2013 at 11:28
0

Try this XPATH:

//dt[contains(text(), "Test")]/self::dt or //dt[contains(text(), "Test")]/following-sibling::dd
2
  • That's what I alternatively used but this is long :)
    – Umair A.
    Commented May 16, 2013 at 9:53
  • 1
    if you are using "1.0", this is the only option Commented May 16, 2013 at 10:15
0

To avoid duplicating the contains test for the dt element, you can rewrite your query so all desired output elements are expressed within the search criterion only once:

//*[contains(self::dt|self::dd/preceding-sibling::dt[1],"Test")]

Explanation: start with the pool of all possible output elements, and of those, choose a either dt or a dd preceded by a dt, where either dt matches the search.

Included this answer to show a way that reduces code duplication and makes it easier to read the expression's union operator |...

-1

According to your example, you might be able to use this xpath, it's shorter and simpler, but it's under the assumption that you're looking for dt, and then you want ALL siblings of dt (not just the following sibling and self). This xpath looks for dt's parent and grabs all its children:

//dt[contains(text(), "Test")]/../*

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.