Greasemonkey: XPath returns no results for .xhtml

2019-07-10 17:40发布

问题:

When running on an xhtml page, xpath doesn't seem to return any results.

var result = document.evaluate( "//a/img", document.body, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );

For example returns an empty result set. What's the problem here, and how do I fix it?

回答1:

xhtml elements are not in null namespace, so you have to pass a namespace resolver to the method:

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 );


回答2:

Ok with this solution, but i'm now using preceding-sibling in the xpathExpression, i try with that :

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];
}

and then :

document.evaluate('//h:' + node.tagName + '/preceding-sibling::' + node.tagName, node, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength

that return always 0 with xhtml.