user1228
user1228

Reputation:

Can XPath match on parts of an element's name?

I want to do this:

//*fu

which returns all nodes whose name ends in fu, such as <tarfu /> and <snafu />, but not <fubar />

Upvotes: 40

Views: 26784

Answers (3)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243599

This answer is for XPath 1.0 where there is no equivalent of the XPath 2.0 standard ends-with() function.

The following XPath 1.0 expression selects all elements in the xml document, whose names end with the string "fu":

//*[substring(name(),string-length(name())-1) = 'fu']

Note that -1 is the offset from the end of name() (the length of "fu" minus one), so that the string comparison performed within substring() starts at the right position from the end of the string.

Similarly, if it was needed to determine whether "asdf" was a suffix of the name, then string-length(name())-3 must be specified.

Upvotes: 52

Chris Marasti-Georg
Chris Marasti-Georg

Reputation: 34690

Do something like:

//*[ends-with(name(), 'fu')]

For a good XPath reference, check out W3Schools.

Upvotes: 41

Identity1
Identity1

Reputation: 1165

I struggled with Dimitre Novatchev's answer, it wouldn't return matches. I knew your XPath must have a section telling that "fu" has length 2.

It's advised to have a string-length('fu') to determine what to substring.

For those who aren't able to get results with his answer and they require solution with xpath 1.0:

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

Finds matches of elements ending with "fu"

or

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

Finds matches to elements ending with "Position"

Upvotes: 2

Related Questions