JavaScript中的XPath属性引用

时间:2010-08-06 16:11:35

标签: javascript encoding xpath

我正在尝试构建一个能够在XPath中正确引用/转义属性的函数。我见过在C#herehere中发布的解决方案,但我在JavaScript中的实现会导致错误“此表达式不是合法表达式”

这是我的功能:

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'”

示例失败输出:

  

的concat( “”, “\” 'HI' “ ”\“”)]

我不明白为什么它是非法表达式(假设双引号被转义),所以我不知道如何修复该函数。

1 个答案:

答案 0 :(得分:2)

\不是XPath字符串文字中的转义字符。 (如果是,你可以反斜杠 - 转义其中一个引号,而不必担心concat!)"\"本身就是一个完整的字符串,然后是{{1} },这没有意义。

因此输出中应该没有反斜杠,它应该类似于:

'hi...

我建议:

concat('"', "'hi'", '"')

它不是那么高效(如果第一个/最后一个字符是双引号,它将包括前导/尾随空字符串段),但这不太重要。

(你真的是指上面的function xpathStringLiteral(s) { if (s.indexOf('"')===-1) return '"'+s+'"'; if (s.indexOf("'")===-1) return "'"+s+"'"; return 'concat("'+s.replace(/"/g, '",\'"\',"')+'")'; } 吗?这是一个非标准的Mozilla语言特征;一个人通常会使用let。)

相关问题