How to convert SOAPBody to String

后端 未结 3 472
梦如初夏
梦如初夏 2020-12-11 01:02

I want to convert SOAPBody to String. What is the best way to do it? Should i first convert it to xml and then convert it into String or we can jsut convert it into String.<

相关标签:
3条回答
  • 2020-12-11 01:42

    Figured this might help -

    private String convertToString (SOAPBody message) throws Exception{
       Document doc = message.extractContentAsDocument();
       StringWriter sw = new StringWriter();
       TransformerFactory tf = TransformerFactory.newInstance();
       Transformer transformer = tf.newTransformer();
       transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
       transformer.setOutputProperty(OutputKeys.METHOD, "xml");
       transformer.setOutputProperty(OutputKeys.INDENT, "yes");
       transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
       transformer.transform(new DOMSource(doc), new StreamResult(sw));
       return sw.toString();
      }
    

    Thanks to the following post - XML Document to String?

    0 讨论(0)
  • 2020-12-11 01:48

    You do not need to convert SOAPBody to XML, because it implements org.w3c.dom.Element interface, thus this is already a valid XML object. You can use org.w3c.dom.ls package to achieve your goal:

       String xmlAsString = null;
       Element element = what-ever-element;
    
       DOMImplementationLS domImplementationLS = (DOMImplementationLS)element.getOwnerDocument().getImplementation().getFeature("LS", "3.0");
       LSSerializer serializer = domImplementationLS.createLSSerializer();
       xmlAsString = serializer.writeToString(element);
    

    You can play with serializer.getDomConfig().setParameter(....) to configure the serializer.

    0 讨论(0)
  • 2020-12-11 02:01

    When starting from a SOAPMessage, the easiest way is to use the writeTo method :

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    soapMessage.writeTo(stream);
    String message = new String(stream.toByteArray(), "utf-8") 
    

    (Above, I assume your SAAJ implementation will use UTF-8, you'd probably want to check).

    If starting from a SOAPBody, then you probably should use XML APIs, seeing SOAPBody is a org.w3.dom.Element, the easiest way would probably be using TrAX :

    SOAPBody element = ... // Whatever
    DOMSource source = new DOMSource(element);
    StringWriter stringResult = new StringWriter();
    TransformerFactory.newInstance().newTransformer().transform(source, new StreamResult(stringResult));
    String message = stringResult.toString();
    

    (Sorry I do not have my IDE right here, can not check if this compiles, but that should be pretty close).

    Please note : A serialized SOAPMessage may not be raw XML : it might be a MIME structure : if the SOAPMessage actually uses SwA (SOAP With Attachment) or MTOM. However, SOAPBody is definitely pure XML.

    0 讨论(0)
提交回复
热议问题