我的 xml 如下。以及默认命名空间 http://september.examples.com/对于
addnumber,firstnumber,secondnumber
XML:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<addnumber xmlns="http://september.examples.com/">
<firstnumber>10</firstnumber>
<secondnumber>22</secondnumber>
</addnumber>
</soapenv:Body>
</soapenv:Envelope>
当我尝试使用以下代码从 Xpath 获取值时
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
xpath.setNamespaceContext(createContext(xml));
String value = xpath.compile("/soapenv:Envelope[1]/soapenv:Body[1]/addnumber[1]/firstnumber[1]").evaluate(document).toString();
我得到的值是空的。由于我在这里给出的 Xpath 是 addnumber[1]/firstnumber[1] 的空命名空间,我如何给出默认命名空间的 xpath?
注意:createContext() 将创建一个包含前缀、URI 的映射
最佳答案
您可以使用任何前缀来表示默认 namespace ,只要它指向相同的 uri。只需在函数 createContext()
中添加另一个指向默认命名空间 uri ( http://september.examples.com/ ) 的前缀,并在 XPath 表达式中使用它即可。
关于java - setNamespaceContext 默认命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22348128/