JavaScript XPath和默认命名空间
我有一些JavaScript/XPath,它不能像我预期的那样工作。(available on jsfiddle)似乎我对一个XML命名空间做了一些错误的事情,使我无法通过它们的节点(标记)名称查询元素。
如果我尝试查询当前节点的所有子节点,我发现元素myElement
没有问题:
var xpathResult = xmlDoc.evaluate( "child::*", rootElement, nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
var queryEl;
if(queryEl = xpathResult.iterateNext()) {
alert("child::* found element " + queryEl.nodeName);
}
else {
alert("child::* found nothing!");
}
.但是,如果我专门以myElement
节点(标记)名称为目标节点,则不会得到任何结果:
/* Now try getting only those children with nodeName `myElement` */
xpathResult = xmlDoc.evaluate( "child::myElement", rootElement, nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
var queryEl;
if(queryEl = xpathResult.iterateNext()) {
alert("child::myElement found element " + queryEl.nodeName);
}
else {
alert("child::myElement found nothing!");
}
我做错了什么?
解决方案
尝试将此作为您的解析程序:
var nsResolver = (function (element) {
var
nsResolver = element.ownerDocument.createNSResolver(element),
defaultNamespace = element.getAttribute('xmlns');
return function (prefix) {
return nsResolver.lookupNamespaceURI(prefix) || defaultNamespace;
};
} (xmlDoc.documentElement));
您还必须选择如下元素:
"child::default:myElement"
// where 'default' can be anything, as long as there is a namespace
进一步阅读:
- https://developer.mozilla.org/en/DOM/document.createNSResolver
- https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript(=>实现默认命名空间解析器)
- http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathNSResolver-lookupNamespaceURI
您的小提琴:http://jsfiddle.net/chKZc/5/(更新)
相关文章