格式化xml文件排版String

代码示例如下:
private String getXmlFormatStr(String str) {
         // 创建String输出流
         StringWriter out = new StringWriter();
         try {
             // 将字符串格式转换成document对象
             Document document = DocumentHelper.parseText(str);

             // 注意,用这种方式来创建指定格式的format
             OutputFormat format = OutputFormat.createPrettyPrint();
             // 包装String流
             XMLWriter writer = new XMLWriter(out, format);

             // 将当前的document对象写入底层流out中
             writer.write(document);
             writer.close();

         } catch (Exception e) {
             e.printStackTrace();
         }
         return out.toString();
    }

猜你喜欢

转载自blog.csdn.net/zqq3436/article/details/80319159