使用 xpath 查找带有撇号(“'")的文本 [英] Using an xpath to find text with an apostrophe ( " ' ")

查看:23
本文介绍了使用 xpath 查找带有撇号(“'")的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我进行了研究和研究,但似乎没有任何效果.假设我想要一个带有文本Tony's Computer"的 xpath.我不能执行以下操作:

I have researched and researched but nothing seems to work. Say I want an xpath with the text "Tony's Computer". I cannot do the following:

//*[contains(text(), 'Tony's Computer')]

出于显而易见的原因,因为 y 和 s 之间的 ' 取消了文本的引号.但这也不起作用:

for obvious reasons, as the ' between the y and s unquotes the text. But nor does this work:

//*[contains(text(), 'Tony\'s Computer')]

还有

//*[contains(text(), 'Tony''s Computer')]

有没有办法摆脱撇号?我找不到任何东西.我能做的最好的事情是使用 Java 执行以下操作(假设 textToLookFor 有要查找的文本):

Is there a way to escape the apostrophe? I cannot find anything. The best I can do is the following with Java (assume textToLookFor has the text to look for):

        String[] fields = textToLookFor.split("'");
        String textx = "";
        for (int indx = 0; indx < fields.length; indx++) {
            String stext = fields[indx];
            String cont = "contains(text(),'" + stext + "') ";
            if (!textx.isEmpty()) {
                textx += " and ";
            }
            textx += cont;
        }
        String xpath = "//*[" + textx + "]";

基本上做了一个

//*[contains(text(),'Tony') and contains(text(), 's Computer')]

我认为这已经足够了.但是,这不是完全匹配.例如,它可以找到托尼和鲍勃的电脑".

which is I suppose good enough. However, it is not an exact match. It could find "Tony and Bob's Computer" for instance.

有没有其他人成功地做到了这一点?我找不到任何其他解决方案.顺便说一句,当我找到元素时,我可以说 String 显示 = ele.getText();然后检查displayed.contains(textToLookFor).

Has anyone else had success doing this? I cannot find any other solutions. By the way, when I find the element I can say String displayed = ele.getText(); and then check that displayed.contains(textToLookFor).

在这种情况下,我首先需要做一个 textToLookFor = textToLookFor.replaceAll("\"", "\\\""); 来转义任何双引号.

In this case I first need to do a textToLookFor = textToLookFor.replaceAll("\"", "\\\""); which escapes any double quotes.

推荐答案

//*[contains(.,"Tony's Computer")]

对我有用.在字符串外部使用双引号.

Works for me. Use double quotes on outside of string.

这篇关于使用 xpath 查找带有撇号(“'")的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆