Javascript Xpath and default namespaces
I have JavaScript / Xpath not working as I expected. ( available at jsfiddle ) It seems that I am doing something wrong with the XML namespace, preventing me from querying my elements by their node (tags).
If I try to query for all child nodes of the current node, I find the element myElement
with no problem:
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!");
}
... but if I specifically target nodes named myElement
node (tag) I don't get any results:
/* 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!");
}
What am I doing wrong?
+3
source to share
1 answer
Try this as your resolver:
var nsResolver = (function (element) {
var
nsResolver = element.ownerDocument.createNSResolver(element),
defaultNamespace = element.getAttribute('xmlns');
return function (prefix) {
return nsResolver.lookupNamespaceURI(prefix) || defaultNamespace;
};
} (xmlDoc.documentElement));
You will also need to select items like this:
"child::default:myElement"
// where 'default' can be anything, as long as there is a namespace
Further reading:
- https://developer.mozilla.org/en/DOM/document.createNSResolver
- https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript (=> Default Namespace Resonator Implementation)
- http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathNSResolver-lookupNamespaceURI
Your fiddle: http://jsfiddle.net/chKZc/5/ (updated)
+5
source to share