How to use "not" in XPath?
Asked Answered
S

5

189

I want to write something of the sort:

//a[not contains(@id, 'xx')]

(meaning all the links who's 'id' attribute doesn't contain the string 'xx')

I can't find the right syntax.

Spiculum answered 11/10, 2009 at 15:40 Comment(0)
U
280

not() is a function in XPath (as opposed to an operator), so

//a[not(contains(@id, 'xx'))]
Unreality answered 11/10, 2009 at 15:45 Comment(2)
is there a way to say grab all the <p> tags but not the <a> tag inside them? imagine something like <p>text text<a class="x">TEXT</a>text text</p> . i want all the text in p but not the TEXT in a. is that possible with XPath? This isn't exactly my case, it's a little more complicated than that but its more or less the same.Impartial
@Ali Does ORDERED_NODE_ITERATOR_TYPE of ./text()|./*[not(self::a)]//text(), passing the paragraph in as the contextNode, solve your use-case? (jsfiddle demo) (note this won't exclude cases of p>* a, where the link isn't top-level, but it could easily be modified to do so.)Evolve
I
42

you can use not(expression) function

or

expression != true()
Insupportable answered 5/1, 2012 at 13:32 Comment(0)
A
19

None of these answers worked for me for python. I solved by this

a[not(@id='XX')]

Also you can use or condition in your xpath by | operator. Such as

a[not(@id='XX')]|a[not(@class='YY')]

Sometimes we want element which has no class. So you can do like

a[not(@class)]
Activism answered 17/3, 2017 at 14:48 Comment(0)
R
2

Use boolean function like below:

//a[(contains(@id, 'xx'))=false]
Rancourt answered 4/11, 2019 at 6:13 Comment(0)
S
0

not() function combined with "and" operator worked in my case. I am using typescript. For example,

contains(text(),'textIWantToBeMatched') and not(contains(text(),'subTextIDoNotWantToBeMatched'))
Selfeffacing answered 27/7, 2023 at 2:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.