Anne van Kesteren

XPath flaw?

So unlike some other highly respected people inside Opera my slogan is not I hate namespaces. I do have a problem with XPath though, I think. Consider this document:

<foo:bar xmlns:foo="http://example.org/a/foo">
 <foo:bar xmlns:foo="http://example.org/b/foo"/>
</foo:bar>

Now in a lot of language you can distinct between the two clearly not identical elements with the qualified name of foo:bar. In CSS you would use the “not yet a W3C Recommendation but really should be” @namespace at-rule. In the DOM you would probably use the getElementsByTagNameNS() method. In XPointer you would use the xmlns() scheme. In XPath you would use //foo:bar. Right.

Comments

  1. No. Microsoft:

    xml.setProperty("SelectionNamespaces",
      "xmlns:fooa='http://example.org/a/foo' xmlns:foob='http://example.org/b/foo'");
    xml.selectNodes("/fooa:bar/foob:bar");
    

    Mozilla:

    var nsResolver = {
      lookupNamespaceURI: function(prefix) {
        switch (prefix) {
          case "fooa": return "http://example.org/a/foo";
          case "foob": return "http://example.org/b/foo";
        }
      }
    };
    xpathEvaluator.evaluate("/fooa:bar/foob:bar", xml, nsResolver, null, null);
    

    Posted by Sjoerd Visscher at

  2. Or to be more precise, the first one is MSXML, the second one is DOM Level 3 XPath.

    Posted by Sjoerd Visscher at

  3. Or to be more clear, the prefixes from the source document shouldn't apply to the xpath expression. You gotta use some other method to declare them to the evaluator.

    Posted by Brock Filer at

  4. Right, I was not talking about XPath being reused in another language. I should probably have mentioned DOM Level 3 XPath in my post. (Which Opera supports as well, although the switch statement might not (yet) been supported.)

    Posted by Anne at

  5. OK, how about //*:bar[namespace-uri()='http://example.org/b/foo']. Is that what you are looking for?

    Posted by Sjoerd Visscher at

  6. I think a new Namespaces discussion mentions exactly what I was trying to say.

    Posted by Anne at

  7. That means that you can never simply pass this around as a string argument in a programming language, for example, without also passing around a whole set of Namespace declarations.

    I agree with what they say, but this is not an XPath problem. It is a problem with any string, as you never know if it might contain prefixes.

    Posted by Sjoerd Visscher at

  8. In all XPath-environments I've worked with, you need to declare the prefixes and their corresponding namespace URI before you start using those prefixes in your XPath queries. Isn't this the case for DOM3 XPath? If so, it needs to be fixed.

    Posted by Asbjørn Ulsberg at