0

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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

exactly, use prefix that point to default namespace uri in XPath instead of just element name without prefix
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.