xhtmlページで実行している場合、xpathは結果を返さないようです。
var result = document.evaluate( "//a/img", document.body, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
たとえば、空の結果セットを返します。ここでの問題は何ですか、どうすれば修正できますか?
xhtmlページで実行している場合、xpathは結果を返さないようです。
var result = document.evaluate( "//a/img", document.body, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
たとえば、空の結果セットを返します。ここでの問題は何ですか、どうすれば修正できますか?
xhtml要素はnull名前空間にないため、名前空間リゾルバーをメソッドに渡す必要があります。
function resolver(prefix) {
return prefix === 'x' ? 'http://www.w3.org/1999/xhtml' : null;
}
var result = document.evaluate( "//x:a/x:img", document.body, resolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
この解決策でOKですが、xpathExpressionで先行兄弟を使用しています。それを試してみます:
function nsResolver(prefix){
var ns = {
'mathml' : 'http://www.w3.org/1998/Math/MathML', // for example's sake only
'h' : 'http://www.w3.org/1999/xhtml'
};
return ns[prefix];
}
その後 :
document.evaluate('//h:' + node.tagName + '/preceding-sibling::' + node.tagName, node, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength
xhtml では常に 0 を返します。