ImportOrg.apache.xml.serialize.OutputFormat;ImportOrg.apache.xml.serialize.OutputFormat;ImportOrg.apache.xml.serialize.XMLSerializer;Importorg.w3c.dom.Document;ImportOrg.xml.sax.InputSource;Importorg.xml.sax.SAXException;ImportJavax.xml.parsers.DocumentBuilder;Importjavax.xml.parsers.DocumentBuilderFactory;Importjavax.xml.parsers.ParserConfigurationException;Importjava.io.IOException;ImportJava.io.StringReader;ImportJava.io.StringWriter;ImportJava.io.Writer;/*** Created by IntelliJ idea. * User:tsaowe * date:11-9-1 * time: Morning 9:13*/ Public classXmlformatter { Publicstring Format (string unformattedxml) {Try { FinalDocument document =Parsexmlfile (unformattedxml); OutputFormat format=NewOutputFormat (document); Format.setlinewidth (65); Format.setindenting (true); Format.setindent (2); Writer out=NewStringWriter (); XMLSerializer Serializer=NewXMLSerializer (out, format); Serializer.serialize (document); returnout.tostring (); } Catch(IOException e) {Throw NewRuntimeException (e); } } PrivateDocument Parsexmlfile (String in) {Try{documentbuilderfactory dbf=documentbuilderfactory.newinstance (); Documentbuilder DB=Dbf.newdocumentbuilder (); InputSource is=NewInputSource (NewStringReader (in)); returnDb.parse (IS); } Catch(parserconfigurationexception e) {Throw NewRuntimeException (e); } Catch(saxexception e) {Throw NewRuntimeException (e); } Catch(IOException e) {Throw NewRuntimeException (e); } } Public Static voidMain (string[] args)throwsexception{String S= "<?xml version=" 1.0 "encoding=" UTF-8 "?><param><dbid>35</dbid><sequence>atgtca< /sequence><maxns>10</maxns><minidentities>90</minidentities><maxevalue>10< /maxevalue><username>admin</username><password>111111</password><type>p</ Type><return_type>2</return_type></param> ";//XML before formattingSystem.out.println (Newxmlformatter (). Format (s)); }}
JAVA XML formatted output