1. 程式人生 > >java格式化xml字串

java格式化xml字串

上篇部落格是利用前臺js來格式化xml字串,那麼這篇部落格則通過後臺java來格式化輸出xml字串。

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

這是關鍵的方法,至於其中需要載入的jar包,在此就不再贅述了。

注意:在後臺格式化xml,都會自帶表頭,若顯示不需要,可以通過字串擷取即可。