【发布时间】:2018-06-14 03:26:47
【问题描述】:
对于给定的 XML 和 XPath(不匹配任何内容),在线 XPath 测试器的工作方式类似于我的以下代码:http://www.xpathtester.com/xpath
import java.io.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
class test {
public static void main(String[] args) throws Exception {
XPathExpression expr = XPathFactory.newInstance().newXPath().compile(
"/A[namespace-uri() = 'some-namespace']"); // This does not select anything, replacing A with * does
// This XPath selects as expected (in all parsers mentioned): /*[namespace-uri() = 'some-namespace']
String xml = "<A xmlns=\"some-namespace\"> </A>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
Document doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
System.out.println("Number of nodes selected: " + nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println("Node name: " + nodes.item(i).getNodeName());
}
}
}
无论文档工厂是否支持命名空间,上述代码都不会选择任何内容。
这符合 XPath 标准吗?还是实现的细微差别?
This 资源提到以下内容:
确实,当 XML 文档使用默认命名空间时,XPath 即使目标文档没有,表达式也必须使用前缀。
为了验证这一点,我更改了 XPath 以包含如下前缀:
/p:A[namespace-uri() = 'some-namespace'] 并添加了一个命名空间解析器,它为前缀 p 返回 URI some-namespace,并且有效。
问题:
1) 有没有一种方法可以使不带前缀的 XPath 表达式在具有默认命名空间的文档上工作?
2) [第二个 XPath 测试器][3] 是如何工作的? (本测试仪不符合标准)
注意:在我的应用程序中,我无法控制收到的文档和 XPath。但两者都保证有效。
【问题讨论】:
标签: java xml xpath namespaces