2015-02-09 104 views
2

我有一個SOAPMessage(發現於javax.xml.soap.SOAPMessage)。如何打印格式化的SOAPMessage?

但是,打印它的唯一方式看起來像是soapMessage.writeTo(System.out);但是,這沒有任何新行,並且有大的SOAPMessage,它可能很難閱讀。

此外,使用System.out.println(soapMessage.toString());剛剛打印出:

[email protected]6c7e77a 

我看着How to pretty print XML from Java?How to print SOAPMessageHow to convert SOAPBody to String但既不修復新行和/或格式化SOAPMessage的問題。

回答

1

如果您不介意在項目中添加其他依賴項,那麼jdom會爲XML提供良好的格式化輸出。

jdom.org的文檔非常值得一看。

這是一個有點令人費解,但你可以在一個JDOM文檔對象編寫XML,然後使用XMLOutputter的對象將其打印在一個漂亮的格式:

// write the SoapMessage to a String called xml 
    File file= new File(pathToFile); 
    file.createNewFile(); 
    FileOutputStream fileOutputStream = new FileOutputStream(file); 
    soapMessage.writeTo(fileOutputStream); 
    fileOutputStream.flush(); 
    fileOutputStream.close(); 
    SAXBuilder b = new SAXBuilder(); 
    Document doc = b.build(file); 
    XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat()); 
    xmlOutputter.output(doc, System.out);