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,都会自带表头,若显示不需要,可以通过字符串截取即可。

你可能感兴趣的:(java格式化xml字符串)