Java - 将Web服务响应(StreamResult)转换为XML以检索子值

时间:2017-06-27 10:24:28

标签: java xml soap stream xmlstreamreader

我的代码完成如下:

        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);

并且它在控制台中有这个输出(结果是在一个OUTPUT行,但我会复制粘贴它像漂亮的xml只是为了更清楚)。

<?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>

所以这完全正常工作。现在如果我想要只有ResponseText或ResponseCode值并将它们放在某些字段中,我如何将这个结果处理成XML以及如何获取该XML元素?

我也看了这个问题Convert StreamResult to string or xml但是我没有看到与我的问题的关系,因为我已经在ANSWER的类代码中了但是我无法处理RESULT(将它作为XML我可以额外处理) 如果我只添加

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

我没有引用已经有输出的RESULT变量。

我也尝试了这个:

result.getOutputStream().toString();

但结果是

java.io.PrintStream@3b9a45b3

result.toString();不会给我想要的结果

如何将此输出转换为XML元素,我可以从中检索并获取特定的XML元素?

提前谢谢你,

1 个答案:

答案 0 :(得分:1)

为了获得所需的元素,例如输出字符串中的ResponseCode, ResponseText是xml,您可以使用以下内容:

因为你的xml有名字空间,所以xpath应该知道这一点。所以你使用xpath.setNameSpaceContext(ns);设置namespacecontext,如下所示

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);
 }