-2

I need to select only the last word using xpath 1.0. I have something like this:

<Example>
 <Ctry> Portugal PT </Ctry>
</Example>

I want to select only the PT word but the order is not exact, i.e: <Ctry> Portugal - Lisbon - PT </Ctry>, but the word i want to extract is always the last one. I've already tried: //*[name()='Example'][substring(., string-length(.) - string-length('PT')+1) = 'PT']/text() but extracts always the whole string.

Can anyone help me please?

  • I'm confused. Is the string always going to end in PT, or it can be something else. For example if it is "Portugal XYZ", you want to get "XYZ"? Does it have to be xpath 1.0 or can you use xpath 2.0? – OldProgrammer Sep 20 '21 at 16:58
  • My bad, it can be something else. And it needs to be xpath 1.0 because I’ve already tried ends with and it doesn’t work – Joana Pinto Sep 20 '21 at 17:34
  • Unfortunately this is going to be difficult in xpath 1.0. See https://stackoverflow.com/a/7548836/5225301 for details. Are you able to process the string in your calling language, perhaps? – Forensic_07 Sep 20 '21 at 22:51

1 Answers1

0

You're selecting a node using the substring as a predicate to filter out other nodes. If you want the substring to be your output, it shouldn't go inside brackets.

substring(//*[name()='Example'], string-length(//*[name()='Example']) - string-length('PT')+1)

note that /text() can be ommited when working with string functions

Yuri Sh
  • 899
  • 1
  • 7