How to select element that contains single quotes using XPath?

无人久伴 提交于 2019-12-24 09:47:49

问题


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


来源:https://stackoverflow.com/questions/37403236/how-to-select-element-that-contains-single-quotes-using-xpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!