0

Is there any XPath pattern that can choose all the html code except the last node? For example , lets say i want all the paragraphs inside the body except the last one in this HTML code: I tried these patterns which returned a null value or error in the expression (I'm using the HAP Testbed v1.1.0.0 to test the patterns on the HTML code):

  • //body//p[last()] != true
  • not(//body//p[last()])
  • //body//not[p[last()]]
  • etc...

Question:

  • Does not() function return a boolean value? - If not, how can I use it for my purpose?
  • Is there any other way to get all the text except the last node?
Jens Erat
  • 37,523
  • 16
  • 80
  • 96
ILoveMom
  • 66
  • 1
  • 7

2 Answers2

4

If you have a path expression exp selecting a set of nodes you can use (exp)[position() != last()] to select all but the last node in the node set. So use (//p)[position() != last()]. If you don't use the parentheses as in //p[position() != last()] you would select /descendant-or-self::node()/p[position() != last()] which would select all p elements that are not the last p child in their respective parent. So in the case of

<root>
  <div>
    <p>1</p>
    <p>2</p>
  </div>
  <div>
    <p>3</p>
    <p>4</p>
  </div>
</root>

that path (//p)[position() != last()] selects the first three p elements while //p[position() != last()] would select the first and the third p elements.

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
0

To get all p tags except the last one and select their text, you can use

//p[position()<last()]//text()

not(...) is indeed a function used inside conditions that returns a boolean.

Community
  • 1
  • 1
Robin
  • 9,415
  • 3
  • 34
  • 45