Can XPath match on parts of an element's name?
Solution 1
Do something like:
//*[ends-with(name(), 'fu')]
For a good XPath reference, check out W3Schools.
Solution 2
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']
Solution 3
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"
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Admin
Updated on March 07, 2020Comments
-
Admin over 4 years
I want to do this:
//*fu
which returns all nodes whose name ends in fu, such as
<tarfu />
and<snafu />
, but not<fubar />
-
Wayne over 12 yearsThis is an XPath 2.0 solution only.
-
LostNomad311 over 9 yearsnote that you can use
local-name()
to omit namespaces in complex XML -
user766308 over 3 yearsThanks for this helpful comment. I was trying to do this with lxml, which supports ends-with, but not on element names. Your answer was exactly what I needed!