2010-08-06 19 views
0

我正在嘗試構建一個將在XPath中正確引用/轉義屬性的函數。我已經看到張貼在C#herehere解決方案,但我在JavaScript執行導致錯誤「這種表達是不合法的表達」JavaScript中的XPath屬性引用

這裏是我的功能:

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( 「」, 「\」 '喜' 「 」\「」)]

我不明白爲什麼它是一個非法的表達式(因爲雙引號被轉義),所以我不知道如何修復這個功能。

回答

2

\不是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的唯一的langauge功能;人們通常會使用var。)

+0

我開發使用Mozilla的平臺客戶端應用程序。這不適用於瀏覽器。謝謝。 – pc1oad1etter 2010-08-06 16:51:34