Bryan
Bryan

Reputation: 159

Xpath - how to exclude nodes that contain attribute?

I have an xpath to obtain all text within text nodes like this:

<text>I want this text</text>

but I do not want to obtain text from nodes that contain an attribute like this:

<text name="contact">I DO NOT want this text</text>

Excluding text nodes that have a "name" attribute should work but I'd prefer to exclude text nodes that have any attribute to be more robust. Is there a way to do this?

The Xpath below works to grab all text except it also grabs what I want excluded.

//*[local-name()='text'][string-length(normalize-space(.))>0]

Upvotes: 4

Views: 1597

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

to exclude text nodes that have any attribute to be more robust

Short xpath expression:

//text[count(@*)=0]

Upvotes: 1

Andersson
Andersson

Reputation: 52665

not(@*) predicate should do the trick:

//*[local-name()='text' and not(@*)][string-length(normalize-space(.))>0]

This should return you only text nodes without any attributes

Upvotes: 4

Related Questions