【发布时间】:2015-09-11 16:17:20
【问题描述】:
我有一个标签,里面有一个唯一的命名空间,只有那个标签。我引入了 XML 命名空间上下文,但我的程序仍然返回 0 个节点。
// Create DocumentBuilderFactory for reading xml file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
factory.setNamespaceAware(true);
Document doc = builder.parse(new InputSource(new StringReader(text)));
// Create XPathFactory for creating XPath Object
XPathFactory xPathFactory = XPathFactory.newInstance();
// Create XPath object from XPathFactory
XPath xpath = xPathFactory.newXPath();
xpath.setNamespaceContext(new NamespaceContext() {
public String getNamespaceURI(String prefix) {
if ("cam".equals(prefix))
return "urn:xxx:1.0:logging";
else if ("soapenv".equals(prefix))
return "http://schemas.xmlsoap.org/soap/envelope/";
else if ("xml".equals(prefix))
return XMLConstants.XML_NS_URI;
return XMLConstants.NULL_NS_URI;
}
// This method isn't necessary for XPath processing.
public String getPrefix(String uri) {
throw new UnsupportedOperationException();
}
// This method isn't necessary for XPath processing either.
public Iterator getPrefixes(String uri) {
throw new UnsupportedOperationException();
}
});
// Compile the XPath expression for getting the response
XPathExpression xPathExpr =
xpath.compile("/cam:message/cam:response/soapenv:Envelope/soapenv:Header/Info[1]/property[@name='response']/text()");
// XPath text example : executing xpath expression in java
// Object result = xPathExpr.evaluate(doc, XPathConstants.NODESET);
// NodeList nodes = (NodeList) result;
// int length = nodes.getLength();
String result1 = (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
XML 看起来像
<cam:message xmlns="urn:xxx:1.0:logging">
<cam:response>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Header xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<Info xmlns="urn:xxx:1.0:xxx.core.xxx.Service1">
<property name="response">some value</property>
</Info>
<Info xmlns="urn:xxx:1.0:xxx.core.xxx.Service2">
<property name="response">i am interested in this value</property>
</Info>
</soapenv:Header>
</soapenv:Envelope>
</cam:response>
</cam:message>
所以标签<Info xmlns="urn:xxx:1.0:xxx.core.xxx.Service2">拥有自己的命名空间。我的程序没有为此返回值。同样有很多 Info 标签。我对命名空间以 Service2 结尾的第二个 Info 标记感兴趣。
【问题讨论】: