1

I would like to select this element using XPath:

<a href="#" onClick="onViewDocument('2016', '1');">2016</a>

So far I have this:

//a[@onClick='onViewDocument('2016', '1');']

Do I need to escape the single quotes around the 2016 and 1?

CJ7
  • 22,579
  • 65
  • 193
  • 321
  • There are solutions for most languages... I.e. XSLT http://stackoverflow.com/questions/8783086/concat-quotation-mark-and-apostrophe-combination-problems, c# http://stackoverflow.com/questions/642125/encoding-xpath-expressions-with-both-single-and-double-quotes... Unfortunately HTML alone does not define a programming language (and it dos not use XPath anywhere to my knowledge)... For more answers - https://www.bing.com/search?q=xpath%20quotes%20concat – Alexei Levenkov May 24 '16 at 02:21
  • @CJ7: You've gotten quality answers to [nearly 500 questions](http://stackoverflow.com/users/327528/cj7?tab=questions&sort=newest), yet your accept ratio is absolutely abysmal, you've only every upvoted 23 times in 6 years, and you've answered less than a tenth as often as you've asked questions. ***Why not give back a bit in some way or other?*** – kjhughes May 24 '16 at 12:22

2 Answers2

2

Simplest usually is to use the alternative of ' or ", depending upon what was already used surrounding the string literal.

If that's not feasible, an alternative is to use &apos; for ' (single quote):

//a[@onClick='onViewDocument(&apos;2016&apos;, &apos;1&apos;);']

Note that you can use &quot; for " (double quote).

Reference: XML Path Language (XPath) Version 1.0:

XPath expressions often occur in XML attributes. The grammar specified in this section applies to the attribute value after XML 1.0 normalization. So, for example, if the grammar uses the character <, this must not appear in the XML source as < but must be quoted according to XML 1.0 rules by, for example, entering it as &lt;. Within expressions, literal strings are delimited by single or double quotation marks, which are also used to delimit XML attributes. To avoid a quotation mark in an expression being interpreted by the XML processor as terminating the attribute value the quotation mark can be entered as a character reference (&quot; or &apos;). Alternatively, the expression can use single quotation marks if the XML attribute is delimited with double quotation marks or vice-versa.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
0

This is for all elements that contain ' in onclick:

//a[contains(@onclick, "'")]

This is for the specific element you're trying to match:

//a[@onClick="onViewDocument('2016', '1')"]
ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110
lauda
  • 4,153
  • 2
  • 14
  • 28