2009-09-17
XPath に文字列を埋め込むときの注意
よく、以下のように XPath に文字列を埋め込む事があります
document.evaluate('//*[@class="' + text + '"]', document, null, 7, null);
まあ、僕もよくこんなコード書くんですけど。
でも、これって
text が外部から来るものだったら、意図通りの動作をしないんですよね
たとえば、以下のような例です。
var text = '"] | /hoge/fuga/piyo | .["'; document.evaluate('//*[@class="' + text + '"]', document, null, 7, null);
というわけで
任意の文字列を XPath の式に変換する JavaScript を書いてみた
以下で試せます
XPath Escaper ←クリック!
コードはこちら
function escapeXPathExpr(text) { var matches = text.match(/[^"]+|"/g); function esc(t) { return t == '"' ? ('\'' + t + '\'') : ('"' + t + '"'); } if (matches) { if (matches.length == 1) { return esc(matches[0]); } else { var results = []; for (var i = 0; i < matches.length; i ++) { results.push(esc(matches[i])); } return 'concat(' + results.join(', ') + ')'; } } else { return '""'; } }
以下のように使います
document.evaluate('//*[@class=' + escapeXPathExpr(text) + ']', document, null, 7, null);
まとめ
急いでコードを書いているときは忘れがちですが。
「文脈」と「任意のデータ」があれば、やっぱりそこにはエスケープの必要性があるということを忘れてはいけませんね
トラックバック - http://d.hatena.ne.jp/amachang/20090917/1253179486
リンク元
- 606 http://b.hatena.ne.jp/articles/200909/425
- 260 http://reader.livedoor.com/reader/
- 147 http://b.hatena.ne.jp/hotentry
- 122 http://www.google.co.jp/search?hl=ja&client=firefox-a&rls=org.mozilla:ja:official&hs=7Bt&q=配列 javascript&btnG=検索&lr=lang_ja
- 116 http://d.hatena.ne.jp/
- 104 http://www.google.co.jp/search?sourceid=navclient&hl=ja&ie=UTF-8&rlz=1T4SUNA_jaJP312JP312&q=IE6+IE7
- 104 http://www.nobodyplace.com/mutter/2009/03/20/140902.php
- 84 http://b.hatena.ne.jp/hotentry/it
- 71 http://www.google.com/reader/view/
- 67 http://www.google.co.jp/search?hl=ja&safe=off&client=firefox-a&rls=org.mozilla:ja-JP-mac:official&hs=M7E&q=戸籍抄本の取り方&btnG=検索&lr=lang_ja
