Che*_*eso 2 javascript xml xpath
我正在研究在Javascript中使用xpath.
我有一个XMLHttpRequest(),它检索KML文档.KML只是XML的一种特殊风格.
我得到文件xhr.responseXML,结果如下:
<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>
Run Code Online (Sandbox Code Playgroud)
然后我想对它执行查询以选择节点.
xmlDom.setProperty("SelectionLanguage", "XPath");
xmlDom.setProperty("SelectionNamespaces","xmlns='http://www.opengis.net/kml/2.2'");
nodeList = xmlDom.selectNodes("/kml/Document/Folder");
Run Code Online (Sandbox Code Playgroud)
但这不适合我.我希望得到至少一个节点,但我得到零.
Q1:谁能解释为什么这不起作用?
当我调查这个时,我惊讶地发现,浏览器中的XML文档不支持跨浏览器的xpath.显然这个selectNodes()功能只是一个IE浏览器吗?
Q2:有谁可以证实这一点?
如果这是真的,那么我应该如何从浏览器中的XML文档中选择跨浏览器节点.
问题3:如何在XML文档上进行跨浏览器的XPath查询?
ps:我特别不关心在"html上做xpath".这是我正在查询的XML文档.
你有:
xmlDom.setProperty("SelectionLanguage", "XPath");
xmlDom.setProperty("SelectionNamespaces","xmlns='http://www.opengis.net/kml/2.2'");
nodeList = xmlDom.selectNodes("/kml/Document/Folder");
Run Code Online (Sandbox Code Playgroud)
必须是:
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");
Run Code Online (Sandbox Code Playgroud)
说明:
XPath表达式中任何未加前缀的名称都被认为是"无命名空间".
因此,表达式:
/kml/Document/Folder
Run Code Online (Sandbox Code Playgroud)
尝试选择名为Folder"无命名空间"的元素,但在提供的文档中,所有元素都在默认(非空)http://www.opengis.net/kml/2.2命名空间中,"无命名空间"中没有元素.这就是上面的XPath表达式无法选择任何元素的原因.
解决方案是将非空前缀的命名空间绑定注册到默认命名空间,最重要的是,使用此前缀为XPath表达式中的任何名称添加前缀.