簡體   English   中英

JavaScript中的XPath屬性引用

[英]XPath attribute quoting in JavaScript

我正在嘗試構建一個將正確引用/轉義XPath中的屬性的函數。 我在這里這里都看到了用C#發布的解決方案,但是我在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;
        }

樣本失敗的輸入:

“‘喜’”

樣本失敗的輸出:

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

我不明白為什么它是一個非法表達式(考慮到雙引號已被轉義),所以我不知道如何修復該函數。

\\不是XPath字符串文字中的轉義字符。 (如果是這樣,您可以反斜杠轉義其中的一個引號,而不必擔心concat !) "\\"本身就是一個完整的字符串,然后跟着'hi... ,該字符串不會說得通。

因此,輸出中應該沒有反斜杠,它應該類似於:

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

我建議:

function xpathStringLiteral(s) {
    if (s.indexOf('"')===-1)
        return '"'+s+'"';
    if (s.indexOf("'")===-1)
        return "'"+s+"'";
    return 'concat("'+s.replace(/"/g, '",\'"\',"')+'")';
}

它的效率不盡如人意(如果第一個/最后一個字符是雙引號,它將包括前導/后綴空字符串段),但這不太可能。

(您的意思真的是let進入上面嗎?這是一種非標准的Mozilla專用語言功能,通常會使用var 。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM