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?

2
  • Can you please split you problem to show just the problem? As a short and (in)valid example? Commented Mar 8, 2012 at 17:07
  • @powtac - Tried... but the code really only creates an XML doc and then makes 2 queries against it. It really is just a test case. Commented Mar 8, 2012 at 17:14

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

In the end XPath wasn't the best solution anyways... but this seems to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.