Home > Software engineering >  SOAPMessage creating XML with empty xmlns attributes
SOAPMessage creating XML with empty xmlns attributes

Time:11-12

I'm trying to create a SOAPMessage that cointains an XML following a specific format, previously i've tried to put the XML, already generated, as a string, however it would turn ">" and "<" characters to &gt; and &lt;, which was not validated correctly by the endpoint. I managed to put the XML as a Node within a Document, which works, however, now the xmlns attributes in the XML, which did have values, are turning empty. For example, given the following message:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
      <SOAP-ENV:Header/>
      <SOAP-ENV:Body>
            <Example xmlns="https://www.example.com"/>
      </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The xmlns="https://www.example.com" ends up as xmlns="", which isn't valid to the endpoint. My code right now is:


MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();

SOAPPart soapPart = soapMessage.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPBody soapBody = envelope.getBody();

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();

Document document = db.newDocument();
Node node = db.parse(new InputSource(new StringReader(xmlString))).getDocumentElement();

Node newNode = node.cloneNode(true);
document.adoptNode(newNode);
document.appendChild(newNode);
soapBody.addDocument(document);

soapMessage.saveChanges();

return soapMessage;

I've tried logging the SOAPMessage and the nodes used throughout to see any changes, and the xmlns always had a value. My next idea would be adding the nodes with xmlns one by one so i could manually set the attribute, however given the approach i already had to add the XML as a single node, that seems complicated, and the resulting code could end up being really convoluted. I need to know if anyone has any clue or idea as to why that's happening and how to fix it in a simpler manner.

CodePudding user response:

Solved it by creating this method:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder builder;  
try{  
    factory.setNamespaceAware(true);
    builder = factory.newDocumentBuilder();  
    Document doc = builder.parse( new InputSource( new StringReader( xmlString ) ) ); 
    return doc;
} catch (Exception e) {  
    e.printStackTrace();  
} 
return null;
  • Related