简体   繁体   中英

XML - XPath to return element that brother element contains certain text

I'm trying to find the correct xpath expression to select the parent of an element where contains a certain text.

In the example below, I would like to select the "span" element with text matching "4" or any other number and the parent matches with the text "Rooms":

My XPath example - matches every "span" inside the "div" element

//div/span[../span[contains(text(), 'Rooms')]]

Source Code

<div>
    <span>4</span>
    <span>Rooms</span>
    <span>and 2 suites</span>
</div>

What I want is to select the "span" element that contains the number four as text, but as the html could change and maybe have just two or one "span" element(s) as the example below:

<div>
    <span>2 Rooms</span>
</div>

or

<div>
    <span>3</span>
    <span>Rooms</span>
</div>

Try this XPath-1.0 expression:

//div/span[contains(text(), 'Rooms')]/preceding-sibling::span[1] | div[count(span)=1 and contains(span/text(), 'Rooms')]/span

It merges the nodeset of the preceding-siblings of span s which contain the text "Rooms" with the first span element if it's the only one (count=1).

Result is:

<span>4</span>
<span>2 Rooms</span>
<span>3</span>

This XPath

//span[contains(.," Rooms") or following-sibling::*[1][self::span]="Rooms"]

will select the span whose string value contains " Rooms" or whose immediately following span sibling has a string value equal to "Rooms".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM