【发布时间】:2020-02-21 07:19:05
【问题描述】:
INPUT_XML:
<?xml version="1.0" encoding="UTF-8">
<root xmlns:ns1="http://path1/schema1" xmlns:ns2="http://path2/schema2">
<ns1:abc>1234</ns1:abc>
<ns2:def>5678</ns2:def>
</root>
在 Java 中,我正在尝试编写 XPath 表达式,它将从上述 INPUT_XML 字符串内容中获取与此属性“xmlns:ns1”对应的值。
我尝试了以下方法:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(INPUT_XML);
String xpathExpression = "/root/xmlns:ns1";
// Create XPathFactory object
XPathFactory xpathFactory = XPathFactory.newInstance();
// Create XPath object
XPath xpath = xpathFactory.newXPath();
// Create XPathExpression object
XPathExpression expr = xpath.compile(xpathExpression);
// Evaluate expression result on XML document
NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
但是上面的代码没有给出指定属性的期望值,即 xmlns:ns1。我严重怀疑 xPathExpression 是错误的。请建议使用正确的 XPath 表达式或解决此问题的正确方法。
【问题讨论】:
标签: java xml xpath xpath-2.0 domxpath