问题
I have xml as follows. And a default namespace http://september.examples.com/ for
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>
When I try to get value from Xpath using the following code
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();
I'm geting empty value. Since the Xpath I have given here is empty namespace of addnumber[1]/firstnumber[1] How can I give xpath of default namespace?
Note:createContext() will crate a map which would contain prefix, URI
回答1:
You can use any prefix to represent default namespace, as long as it points to the same uri. Simply add another prefix pointing to default namespace uri (http://september.examples.com/) in the function createContext()
, and use it in XPath expression.
Related question : https://stackoverflow.com/a/6392700/2998271
回答2:
Unprefixed names in XPath 1.0 always mean "no namespace", this is fixed by the spec:
A QName in the node test is expanded into an expanded-name using the namespace declarations from the expression context. This is the same way expansion is done for element type names in start and end-tags except that the default namespace declared with xmlns is not used: if the QName does not have a prefix, then the namespace URI is null. [my bold]
You must bind a prefix to the http://september.examples.com/
namespace in your context and use that prefix in the XPath expression.
来源:https://stackoverflow.com/questions/22348128/setnamespacecontext-for-default-namespace