187

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.

U. Windl
  • 3,480
  • 26
  • 54
Guy
  • 14,178
  • 27
  • 67
  • 88

5 Answers5

279

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

//a[not(contains(@id, 'xx'))]
Syscall
  • 19,327
  • 10
  • 37
  • 52
James Sulak
  • 31,389
  • 11
  • 53
  • 57
  • is there a way to say grab all the

    tags but not the tag inside them? imagine something like

    text textTEXTtext text

    . 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.

    – CodeMonkey Sep 03 '19 at 13:07
  • @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](https://jsfiddle.net/fkg14a26/)\) *(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.)* – JamesTheAwesomeDude Sep 13 '22 at 20:24
42

you can use not(expression) function

or

expression != true()
Abdelhameed Mahmoud
  • 2,118
  • 2
  • 22
  • 17
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)]
Harun ERGUL
  • 5,770
  • 5
  • 53
  • 62
2

Use boolean function like below:

//a[(contains(@id, 'xx'))=false]
frianH
  • 7,295
  • 6
  • 20
  • 45
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'))
toyota Supra
  • 3,181
  • 4
  • 15
  • 19