import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringReader;
import java.io.StringWriter;
public class XmlPrettyPrint {
private static String format( final String xml ) throws Exception {
final var transformer = TransformerFactory.newInstance().newTransformer();
final var result = new StreamResult( new StringWriter() );
final var dbf = DocumentBuilderFactory.newInstance();
final var db = dbf.newDocumentBuilder();
final var is = new InputSource( new StringReader( xml ) );
final var source = new DOMSource( db.parse( is ) );
transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount",
String.valueOf( 2 ) );
transformer.transform( source, result );
return result.getWriter().toString();
}
}
用法示例:
final var unformattedXml = "<hello><world/></hello>";
final var formattedXml = XmlPrettyPrint.format( unformattedXml );
结果:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<hello>
<world/>
</hello>
注意:结果可能因 Java 版本而异。搜索特定于您的平台的解决方法。