0
我使用下面的代碼打印出更漂亮的XML字符串:防止包裝時非常印刷XML字符串
private String prettyFormat(String xml) throws TransformerException, ParserConfigurationException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
String formattedString = null;
try {
final InputSource src = new InputSource(new StringReader(xml));
final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
System.setProperty(DOMImplementationRegistry.PROPERTY,"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");
final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
final LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
writer.getDomConfig().setParameter("xml-declaration", Boolean.FALSE);
formattedString = writer.writeToString(document);
} catch (Exception e) {
throw new RuntimeException(e);
}
return formattedString;
}
我的問題是,它包裹長的線,從而使這樣的:
<message code="272" coeMsgName="CCR_I-Credit-Control-Initial" endtoend="AUTO" error="false" hopbyhop="AUTO" proxiable="true" request="true" retransmit="false">
變成這樣:
<message code="272" coeMsgName="CCR_I-Credit-Control-Initial"
endtoend="AUTO" error="false" hopbyhop="AUTO" proxiable="true"
request="true" retransmit="false">
似乎沒有進一步的調整avalable上[格式漂亮地打印](http://xerces.apache.org/ Xerces2的-J/javadocs中/ API /組織/ W3C/DOM/LS/LSSerializer.html)。你可以看看滾動你自己的美麗的打印機,例如沒有換行[here](http://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java) – StuartLC 2015-02-05 15:41:54
後處理輸出可能是另一種選擇。 - 但這種格式有什麼不好 - 對我來說非常漂亮。 – laune 2015-02-05 15:47:05