XQuery使用'单'引号查找文本 [英] XQuery looking for text with 'single' quote
问题描述
我不知道如何使用XPATHs搜索包含单引号的文本。
I can't figure out how to search for text containing single quotes using XPATHs.
例如,我已经添加了一个引号到这个问题的标题。以下行
For example, I've added a quote to the title of this question. The following line
$x("//*[text()='XQuery looking for text with 'single' quote']")
返回一个空数组
但是,如果我尝试以下
$x("//*[text()=\"XQuery looking for text with 'single' quote\"]")
它确实返回页面标题的链接,但我希望能够接受单引号和双引号,所以我不能仅仅为单/双引号定制。
It does return the link for the title of the page, but I would like to be able to accept both single and double quotes in there, so I can't just tailor it for the single/double quote.
您可以在此页面的chrome或firebug的控制台中尝试。
You can try it in chrome's or firebug's console on this page.
推荐答案
这是一个hackaround感谢Dimitre Novatchev),这将允许我搜索xpath中的任何文本,无论它包含单引号还是双引号。在JS中实现,但可以轻松地翻译成其他语言
Here's a hackaround (Thanks Dimitre Novatchev) that will allow me to search for any text in xpaths, whether it contains single or double quotes. Implemented in JS, but could be easily translated to other languages
function cleanStringForXpath(str) {
var parts = str.match(/[^'"]+|['"]/g);
parts = parts.map(function(part){
if (part === "'") {
return '"\'"'; // output "'"
}
if (part === '"') {
return "'\"'"; // output '"'
}
return "'" + part + "'";
});
return "concat(" + parts.join(",") + ")";
}
如果我正在寻找我正在阅读Harry Potter
我可以做以下
If I'm looking for I'm reading "Harry Potter"
I could do the following
var xpathString = cleanStringForXpath( "I'm reading \"Harry Potter\"" );
$x("//*[text()="+ xpathString +"]");
// The xpath created becomes
// //*[text()=concat('I',"'",'m reading ','"','Harry Potter','"')]
这是一个(短得多的)Java版本,它与JavaScript完全相同,如果您删除类型信息,感谢 https://stackoverflow.com/users/1850609/acdcjunior
Here's a (much shorter) Java version. It's exactly the same as JavaScript, if you remove type information. Thanks to https://stackoverflow.com/users/1850609/acdcjunior
String escapedText = "concat('"+originalText.replace("'", "', \"'\", '") + "', '')";!
这篇关于XQuery使用'单'引号查找文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!