61

I am trying to find an input element with dynamic id name always ending with "register". So far I tried this

"//input[@id[ends-with(.,'register')]]"

and this

"//input[ends-with(@id,'register')]"

none of these result in an element. What am I doing wrong? At the same time this works:

"//input[@id[contains(.,'register')]]"

Here's the part of source:

<td class="input">
<input id="m.f0.menu.f2.volumeTabs.BLOCK_COMMON.tcw.form.register" name="m.f0.menu.f2.volumeTabs.BLOCK_COMMON.tcw.form.register" class="aranea-checkbox" type="checkbox"> </td>
casper
  • 1,391
  • 2
  • 16
  • 29
  • 4
    which version of xpath do you use? – donfuxx Mar 16 '14 at 12:42
  • 2
    In addition to the XPath version (1.0 does not have `ends-with()`), can you also show us some XML that shows the problem? – Thomas W Mar 16 '14 at 12:59
  • 1
    ehm, not sure - how can I check version? I am testing via Google Chrome's console. Which version is Chrome using? – casper Mar 16 '14 at 13:34
  • 1
    at least show sample XML that can reproduce the problem. Any chance that value of id attribute has whitespace at the end, so it doesn't precisely ends with 'register'? – har07 Mar 16 '14 at 13:53
  • possible duplicate of [Why does xmlstarlet say there's no 'ends-with' function?](http://stackoverflow.com/questions/21602118/why-does-xmlstarlet-say-theres-no-ends-with-function) – Jens Erat Mar 16 '14 at 23:02

2 Answers2

125

The ends-with function is part of xpath 2.0 but browsers (you indicate you're testing with chrome) generally only support 1.0. So you'll have to implement it yourself with a combination of string-length, substring and equals

substring(@id, string-length(@id) - string-length('register') +1) = 'register'
Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
4

The accepted answer by Ian Roberts uses the @id attribute twice in his solution.

In this case I prefer to put the predicate on that @id like this:

//input[@id[substring(.,string-length(.) - string-length('register') + 1) = 'register']]
Siebe Jongebloed
  • 3,906
  • 2
  • 14
  • 19