我有一个包含XML的Java字符串,没有换行或缩进。我想将其转换为格式正确的XML字符串。我该怎么做呢?
String unformattedXml = "<tag><nested>hello</nested></tag>"; String formattedXml = new [UnknownClass]().format(unformattedXml);
注意:我的输入是String。我的输出是String。
(基本)模拟结果:
<?xml version="1.0" encoding="UTF-8"?> <root> <tag> <nested>hello</nested> </tag> </root>
Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); //initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); transformer.transform(source, result); String xmlString = result.getWriter().toString(); System.out.println(xmlString);
注意:结果可能因Java版本而异。搜索特定于你的平台的解决方法。