How to select element that contains single quotes

2019-07-25 14:42发布

问题:

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?

回答1:

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.



回答2:

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')"]