java格式化xml字串
阿新 • • 發佈:2018-11-01
上篇部落格是利用前臺js來格式化xml字串,那麼這篇部落格則通過後臺java來格式化輸出xml字串。
這是關鍵的方法,至於其中需要載入的jar包,在此就不再贅述了。public String formatXML(String inputXML) throws Exception { SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(inputXML)); String requestXML = null; XMLWriter writer = null; if (document != null) { try { StringWriter stringWriter = new StringWriter(); OutputFormat format = new OutputFormat(" ", true); writer = new XMLWriter(stringWriter, format); writer.write(document); writer.flush(); requestXML = stringWriter.getBuffer().toString(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } return requestXML; }
注意:在後臺格式化xml,都會自帶表頭,若顯示不需要,可以通過字串擷取即可。