Java可以使用自带的API将XML格式化,直接贴上工具类:
public static String prettyPrintByTransformer(String xmlString, int indent, boolean ignoreDeclaration) {try {InputSource src = new InputSource(new StringReader(xmlString));Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src);TransformerFactory transformerFactory = TransformerFactory.newInstance();transformerFactory.setAttribute("indent-number", indent);Transformer transformer = transformerFactory.newTransformer();transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ignoreDeclaration ? "yes" : "no");transformer.setOutputProperty(OutputKeys.INDENT, "yes");Writer out = new StringWriter();transformer.transform(new DOMSource(document), new StreamResult(out));return out.toString();} catch (Exception e) {throw new RuntimeException("Error occurs when pretty-printing xml:\n" + xmlString, e);}
}
测试:
import org.w3c.dom.Document;
import org.xml.sax.InputSource;import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
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;
import java.io.Writer;public class Test {public static void main(String[] args) throws TransformerConfigurationException {String xml = "\n" +"\n" +"\n" +"yarn.acl.enabletrueyarn.admin.acl*\n";System.out.println(prettyPrintByTransformer(xml, 2, false));}
}