JavaScript中的XPath属性引用 [英] XPath attribute quoting in JavaScript
问题描述
我正在尝试构建一个将在XPath中正确引用/转义属性的函数。我已经在C#中的这里和此处,但我在JavaScript中的实现导致错误此表达式不是合法表达式
I am trying to build a function that will properly quote/escape an attribute in XPath. I have seen solutions posted in C# here and here, but my implementation in JavaScript results in an error "This expression is not a legal expression"
这是我的函数:
function parseXPathAttribute(original){
let result = null;
/* If there are no double quotes, wrap in double quotes */
if(original.indexOf("\"")<0){
result = "\""+original+"\"";
}else{
/* If there are no single quotes, wrap in single quotes */
if(original.indexOf("'")<0){
result = "'"+original+"'";
}else{ /*Otherwise, we must use concat() */
result = original.split("\"")
for (let x = 0;x<result.length;x++){
result[x] = result[x].replace(/"/g,"\\\"");
if (x>0){
result[x] = "\\\""+result[x];
}
result[x] = "\""+result[x]+"\"";
}
result = result.join();
result = "concat("+result+")";
}
}
return result;
}
样本输入失败:
'hi'
"'hi'"
输出失败的示例:
concat(, \'hi' , \)]
concat("","\"'hi'","\"")]
我不明白为什么这是一个非法表达(假设双引号是转义),所以我不知道该如何解决该功能。
I don't understand why it is an illegal expression (given that the double quotes are escaped), so I don't know how to fix the function.
推荐答案
\
不是XPath字符串文字中的转义字符(如果是,则可以反斜杠转义其中一个)引号,而不必担心 concat
!) \
本身就是一个完整的字符串,然后是'hi ...
,这没有任何意义。
\
is not an escape character in XPath string literals. (If it was, you could just backslash-escape one of the quotes, and never have to worry about concat
!) "\"
is a complete string in itself, which is then followed by 'hi...
, which doesn't make sense.
所以应该没有反斜杠在您的输出中,应该类似于:
So there should be no backslashes in your output, it should look something like:
concat('"', "'hi'", '"')
我建议:
function xpathStringLiteral(s) {
if (s.indexOf('"')===-1)
return '"'+s+'"';
if (s.indexOf("'")===-1)
return "'"+s+"'";
return 'concat("'+s.replace(/"/g, '",\'"\',"')+'")';
}
效率不如预期(其中包括前导/如果第一个/最后一个字符是双引号,则在空字符串段的末尾尾随空格),但这不太重要。
It's not quite as efficient as it might be (it'll include leading/trailing empty string segments if the first/last character is a double-quote), but that's unlikely to matter.
(您真的是说 let
呢?这是非标准的Mozilla专用语言功能;通常会使用 var
。)
(Do you really mean let
in the above? This is a non-standard Mozilla-only langauge feature; one would typically use var
.)
这篇关于JavaScript中的XPath属性引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!