Search code examples
javaxmlsoapstreamxmlstreamreader

Java - convert web service response (StreamResult) to XML in order to retrieve child value


My code finishes like this:

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        Source sourceContent = soapResponse.getSOAPPart().getContent();
        System.out.print("\nResponse SOAP Message = ");
        StreamResult result = new StreamResult(System.out);
        transformer.transform(sourceContent, result);

and it has this output in console(result is in ONE OUTPUT line but I will copy paste it like pretty xml just to be more clear).

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <VerifyEmailResponse xmlns="http://ws.cdyne.com/">
      <VerifyEmailResult>
        <ResponseText>Mail Server will accept email</ResponseText>
        <ResponseCode>3</ResponseCode>
        <LastMailServer>gmail-smtp-in.l.google.com</LastMailServer>
        <GoodEmail>true</GoodEmail>
      </VerifyEmailResult>
    </VerifyEmailResponse>
  </soap:Body>
</soap:Envelope>

So this works completly OK.Now if I want to have just ResponseText or ResponseCode value and to put those in some fields how can I process this result to XML and how to get that XML element?

Also I looked this question Convert StreamResult to string or xml but I do not see relation to my our question since I already have in my class code from the ANSWER but I am not able to process RESULT (to have it as XML which I can process additionally) if I add just

StringWriter writer = new StringWriter();
String resultString2=writer.toString();

I do not have reference to my RESULT variable which already has output.

I tried this also:

result.getOutputStream().toString();

but result is

java.io.PrintStream@3b9a45b3

result.toString(); does not give me desired result either

How to get this output to XML element from which I can retrieve and get specific XML element?

Thank you in advance,


Solution

  • In order to get the desired elements for e.g. ResponseCode, ResponseText from the output string which is an xml , you could use the following:

    Because your xml has namespaces, xpath should be aware of that. So you set namespacecontext using xpath.setNameSpaceContext(ns); like below

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    Source sourceContent = soapResponse.getSOAPPart().getContent();
    System.out.print("\nResponse SOAP Message = ");
    
    StringWriter sw = new StringWriter();
    transformer.transform( sourceContent, new StreamResult( sw ) );
    
    InputSource inputSource = new InputSource( new StringReader( sw.toString() ) );
    XPath xpath = XPathFactory.newInstance().newXPath();
    
    javax.xml.namespace.NamespaceContext ns = new javax.xml.namespace.NamespaceContext()
     {
    
        @Override
        public String getNamespaceURI(String prefix) {
            if ( "soap".equals( prefix ) )
            {
                return "http://schemas.xmlsoap.org/soap/envelope/";
            }
            else if ( "xsi".equals( prefix ) )
            {
                return "http://www.w3.org/2001/XMLSchema-instance";
            }
            else if ( "xsd".equals( prefix ) )
            {
                return "http://www.w3.org/2001/XMLSchema";
            }
            else if ( "xml".equals( prefix ) )
            {
                return javax.xml.XMLConstants.XML_NS_URI;
            }
            else if( "responsens".equals( prefix ) )
            {
                return "http://ws.cdyne.com/";
            }
    
    
            return javax.xml.XMLConstants.NULL_NS_URI;
    
        }
    
        @Override
        public String getPrefix(String namespaceURI) {
                    return null;
        }
    
        @Override
        public Iterator<?> getPrefixes(String namespaceURI) {
                    return null;
        }
    
     };
     xpath.setNamespaceContext(ns);
     Object obj = xpath.evaluate("//responsens:ResponseText/text()", inputSource, XPathConstants.STRING );
     if ( obj != null ) 
     { 
           String responseText = obj.toString();
           System.out.println("Response text : " + responseText);
     }
    
     inputSource = new InputSource( new StringReader( sw.toString() ) );
      //To get Response code:
     obj = xpath.evaluate("//responsens:ResponseCode/text()", inputSource, XPathConstants.STRING );
     if ( obj != null ) 
     { 
        String responseCode = obj.toString();
        System.out.println("Response code : " + responseCode);
     }