23

Given

<foo>
  <bar baz="Hello, World!">
</foo>

How do I all but the last 4 characters of @baz? One of my attempts was:

/foo/bar/@baz[substring( ., 0, -4 )]
Kit Sunde
  • 35,972
  • 25
  • 125
  • 179

3 Answers3

23

Use:

substring(/foo/bar/@baz, string-length(/foo/bar/@baz)-3) 

Do note the 3 in the expression.

The following is wrong:

substring(/foo/bar/@baz, string-length(/foo/bar/@baz)-4) 

because this returns the last 5 characters of the string value of the baz attribute.

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
  • @Volkirith, The phrase in the question "How do I all but the last 4 characters" is ambiguous -- maybe it meant "How do I **skip** all but the last 4 characters" in which case the answer is correct. We can't know for sure, but the fact that the answer was accepted kinda confirms this guess. Of course, had it been the other way around (the meaning you suggest in your comment). the solution is easy enough: `substring(/foo/bar/@baz, 1, string-length(/foo/bar/@baz)-3)` Do note that recently moderators and other people have been "correcting" questions -- leading to this mess :( – Dimitre Novatchev Jan 16 '19 at 15:15
8

try this: substring-before(/foo/bar/@baz,"rld!")

albertjan
  • 7,739
  • 6
  • 44
  • 74
ecciethetechie
  • 157
  • 1
  • 2
4

That's actually not so bad, but IIRC substring doesn't like negative indices. I tried

substring(/foo/bar/@baz, string-length(/foo/bar/@baz)-4)

Which gave me the expected result.

Jan Thomä
  • 13,296
  • 6
  • 55
  • 83