24

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 )]
0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@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 :(
8

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.