XML字符串格式化

阅读更多
 public static String formatXml(String xml) {
        String result = xml;

        SAXReader saxReader = new SAXReader();
        Document document = null;
        StringWriter writer = null;
        try {
            document = saxReader.read(new ByteArrayInputStream(xml.getBytes()));
            // 创建输出格式
            OutputFormat format = OutputFormat.createPrettyPrint();
            // 制定输出xml的编码类型
            format.setEncoding("UTF-8");

            writer = new StringWriter();
            // 创建一个文件输出流
            XMLWriter xmlwriter = new XMLWriter(writer, format);
            // 将格式化后的xml串写入到文件
            xmlwriter.write(document);
            result = writer.toString();

        } catch (Exception e) {
            // 日志
        } finally {
            if (writer != null) {
                IOUtils.closeQuietly(writer);
            }
        }
        return result;
    }

你可能感兴趣的:(常见问题)