Greasemonkey: XPath returns no results for .xhtml page

谁说胖子不能爱 提交于 2020-01-04 09:25:20

问题


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.



来源:https://stackoverflow.com/questions/454143/greasemonkey-xpath-returns-no-results-for-xhtml-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!