<tag><tag>test</tag></tag>
A string like
<tag>
<tag>test</tag>
</tag>
I want to convert it like this.
There seem to be various theories about how to do it, but I combined some of them as follows.
static public String formatXml(String xml) {
try {
InputStream bais = new ByteArrayInputStream(xml.getBytes("utf-8"));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(bais);
doc.setXmlStandalone(true);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
return header + "\n" + xmlString;
} catch (Exception e) {
e.printStackTrace();
}
return xml;
}
Recommended Posts