'NAMESPACE_ERR after using setNamespaceAware

I'm getting this error: org.w3c.dom.DOMException: NAMESPACE_ERR

I have made use of documentBuilderFactory.setNamespaceAware(true), but I'm still getting the error.

Firstly, I used JAXB to marshal the body of my SOAP request:

JAXBContext jaxbContext = JAXBContext.newInstance(CelsiusToFahrenheit.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(request, sw);
String xmlBody = sw.toString();

Next, I created the SOAP envelope for the body:

MessageFactory factory = MessageFactory.newInstance();
SOAPMessage message = factory.createMessage();
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPBody body = envelope.getBody();

Document document = stringToDocument(xmlBody);
body.addDocument(document);

Then I created the document:

private static Document stringToDocument(String xml) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder;
        try {
            builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(xml)));
            return doc;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

For some reason I'm still getting this error:

org.w3c.dom.DOMException: NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.

This is what the body of my request (xmlBody) looks like:

<CelsiusToFahrenheit xmlns="https://www.w3schools.com/xml/">
      <Celsius>25</Celsius>
</CelsiusToFahrenheit>

Initially my code did not have the documentBuilderFactory.setNamespaceAware(true). I've searched for a solution but unfortunately haven't come across one.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source