2

I am looking into the use of xpath from within Javascript.

I have an XMLHttpRequest(), which retrieves a KML document. KML is just a particular flavor of XML.

I get the document via xhr.responseXML, the result looks like this:

<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
    <Style id="1">
      <IconStyle>
        <color>7f66CC33</color>
        <Icon>
          <href />
        </Icon>
      </IconStyle>
       ...
    </Style>
    <Folder>
      ....
    </Folder>
  </Document>
</kml>

Then I want to perform queries on it to select nodes.

    xmlDom.setProperty("SelectionLanguage", "XPath");
    xmlDom.setProperty("SelectionNamespaces","xmlns='http://www.opengis.net/kml/2.2'");
    nodeList = xmlDom.selectNodes("/kml/Document/Folder");

But this isn't working for me. I expect to get at least one node, but I get zero.

Q1: Can anyone explain why this is not working?

As I was looking into this, I discovered to my surprise that xpath is not supported in XML Documents in the browser, in a cross-browser fashion. Apparently the selectNodes() function is an IE-only thing?

Q2: Can anyone confirm this?

If this is true, then what should I be doing for cross-browser node selection from an XML document, from within the browser.

Q3: How do I do cross-browser XPath queries, on an XML document?


ps: I specifically don't care about doing "xpath on html". It's an XML document I'm querying.

Cheeso
  • 189,189
  • 101
  • 473
  • 713
  • ps: here's a cross-browser javascript class to do XPath. http://jmvidal.cse.sc.edu/talks/javascriptxml/xpathexample.html This did not work for me, on FF6, and also I did not like the class name ad shape. So I changed it a little to fit my needs, see http://stackoverflow.com/questions/183369/cross-browser-xpath-implementation-in-javascript/7476028#7476028 – Cheeso Sep 19 '11 at 19:13

1 Answers1

6

You have:

xmlDom.setProperty("SelectionLanguage", "XPath"); 
xmlDom.setProperty("SelectionNamespaces","xmlns='http://www.opengis.net/kml/2.2'"); 
nodeList = xmlDom.selectNodes("/kml/Document/Folder"); 

Must be:

xmlDom.setProperty("SelectionLanguage", "XPath"); 
xmlDom.setProperty("SelectionNamespaces","xmlns:x='http://www.opengis.net/kml/2.2'"); 
nodeList = xmlDom.selectNodes("/x:kml/x:Document/x:Folder"); 

Explanation:

Any unprefixed name in an XPath expression in considered to beling to "no namespace".

Therefore, the expression:

/kml/Document/Folder

attempts to select elements named Folder that are in "no namespace" but in the provided documents all elementa are in the default (non-null) http://www.opengis.net/kml/2.2 namespace and there is no element in "no namespace". This is why the XPath expression above can't select any element.

The solution is to register a namespace binding of a non-empty prefix to the default namespace and most importantly, use this prefix to prefix any name in the XPath expression.

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431