Xeoncross
Xeoncross

Reputation: 57294

XPath to select div with single child ignoring whitespace?

I would like to find unneeded nested divs and clean them up by looking for a div which has only a single element (ignoring whitespace nodes).

<div>
    <div>Text in nested div</div>
</div>

So far I have the following xpath which seems to partially work.

//div[count(node()[normalize-space()]) = 1]

Upvotes: 2

Views: 976

Answers (2)

JLRishe
JLRishe

Reputation: 101748

Please give this a try:

//div[not(*[2]) and div and not(text()[normalize-space()])]

This should select divs that have a single child element and no non-whitespace child text nodes.

Upvotes: 1

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243579

Use this short and efficient expression:

//div[*[1][self::div]][not(*[2]|text()[normalize-space()])]

Upvotes: 1

Related Questions