如何从Java中漂亮地打印XML?

40 浏览
0 Comments

如何从Java中漂亮地打印XML?

我有一个Java字符串,其中包含没有换行符或缩进的XML。我想将其转换为格式良好的XML字符串。我该怎么做?

String unformattedXml = "hello";
String formattedXml = new [UnknownClass]().format(unformattedXml);

注:我的输入是一个字符串。我的输出是一个字符串

(基本)模拟结果:



  
    hello
  

admin 更改状态以发布 2023年5月20日
0
0 Comments

基于此答案的更简单的解决方案:

public static String prettyFormat(String input, int indent) {
    try {
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
        transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
        Transformer transformer = transformerFactory.newTransformer(); 
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Exception e) {
        throw new RuntimeException(e); // simple exception handling, please review it
    }
}
public static String prettyFormat(String input) {
    return prettyFormat(input, 2);
}

测试用例:

prettyFormat("aaa");

返回值:



  aaa
  

//忽略:原始编辑只需要在代码中的类名称中添加缺少的s,冗余的六个字符添加到SO的6个字符验证上

0
0 Comments

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版本而异。请搜索特定于您平台的解决方法。

0