Reputation: 192577
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.
Upvotes: 2
Views: 2033
Reputation: 243529
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.
Upvotes: 7