d-b
d-b

Reputation: 971

Make XPath stop at a certain depth?

I have the following HTML

<span class="medium bold day-time-clock">
            09:00
            <div class="tooltip-box first-free-tip ">
                <div class="tooltip-box-inner">
                    <span class="fa fa-clock-o"></span>
                    Some more text
                </div>
            </div>
        </span>

I want an XPath that only gets the text 09:00, not Some more text NOT using text()[1] because that causes other problems. My current XPath looks like this

("//span[1][contains(@class, 'day-time-clock')]/text()")

I want one that ignores this whole part of the HTML

    <div class="tooltip-box first-free-tip ">
        <div class="tooltip-box-inner">
            <span class="fa fa-clock-o"></span>
            Some more text
        </div>
    </div>

Upvotes: 2

Views: 803

Answers (3)

Jack Fleeting
Jack Fleeting

Reputation: 24930

I think (if I understand you correctly) that

"..//div[contains(@class, 'tooltip-box')]/parent::span"

gets you there.

Upvotes: 0

zx485
zx485

Reputation: 29052

You can limit the level of descendant:: nodes with position().
So the following expression does work:

span/descendant::node()[2 > position()]

Adjust the number in the predicate to your needs, 2 is only an example. A disadvantage of this approach is that the counting of the descendants is only accurate for the first child in the descending tree.


Another approach is limiting the both: the ancestors and the descendants:

span/descendant::node()[3 > count(ancestor::*) and 1 > count(descendant::*)]

Here, too, you have to adjust the numbers in the predicates to get any useful results.

Upvotes: 1

fpsthirty
fpsthirty

Reputation: 185

Use normalize-space() for select all non-whitespace nodes of the document:

//span[contains(@class, 'day-time-clock')]/text()[normalize-space()]

Upvotes: 0

Related Questions