2009-01-17 13 views
2

在xhtml页面上运行时,xpath似乎没有返回任何结果。Greasemonkey:XPath不会返回.xhtml页面的结果

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

例如返回一个空的结果集。这里有什么问题,我该如何解决?

回答

6

XHTML元素不是空的命名空间,所以你要一个namespace resolver传递给方法:

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

好了这个解决方案,但现在我使用的前同辈在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。