SetNamespaceContext for the default namespace

I have xml as follows. And the default namespace is 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 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 am getting empty. Since the Xpath I gave here is an empty namespace addnumber [1] / firstnumber [1] How can I give the xpath of the default namespace?

Note. createContext () will display the map containing the prefix, URI

0


source to share


2 answers


You can use any prefix to represent the default namespace as long as it points to the same uri. Just add another prefix pointing to the default uri namespace ( http://september.examples.com/ ) in the function createContext()

and use it in the XPath expression.



Related question: fooobar.com/questions/109804 / ...

+1


source


Unprefixed names in XPath 1.0 always means "no namespace", this is fixed by the specification :

The QName in the test node is expanded to the expanded name using namespace declarations from the context of the expression. Extension is done for element type names in start and end tags in the same way, except that the default namespace declared with xmlns is not used: if the QName is not prefixed, then the namespace URI is null . [my bold]



You must bind the prefix to a namespace http://september.examples.com/

in your context and use that prefix in your XPath expression.

0


source







All Articles