5

I have some JavaScript/Xpath which isn't working as I would expect. (available on jsfiddle) It would seem that I'm doing something wrong with an XML namespace, preventing me from querying for my elements by their node (tag) names.

If I try querying for all child nodes of the current node, I find the element myElement without 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 the nodes with myElement node (tag) names I get no 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?

Richard JP Le Guen
  • 28,364
  • 7
  • 89
  • 119

1 Answers1

8

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 have to select the elements like this:

"child::default:myElement"
// where 'default' can be anything, as long as there is a namespace

Further reading:

Your fiddle: http://jsfiddle.net/chKZc/5/ (updated)

Yoshi
  • 54,081
  • 14
  • 89
  • 103