dom4j格式化(美化)生成(导出)的xml

版权声明: https://blog.csdn.net/Soul_Programmer_Swh/article/details/84289948

引用jar包:dom4j-1.6.1-sources.jar

方法实现:

    private String xmlPretty(Document document) {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setIndent("    ");
        format.setEncoding(document.getXMLEncoding());
        try {
            StringWriter out = new StringWriter();
            XMLWriter writer = new XMLWriter(out, format);
            writer.write(document);
            writer.flush();
            return out.toString();
        } catch (IOException e) {
            String xml = document.asXML();
            logger.warn("format xml failed, use doc.asXml(). xml : [{}]", xml);
            return xml;
        }
    }

jar包代码:

    /**
     * A static helper method to create the default pretty printing format. This
     * format consists of an indent of 2 spaces, newlines after each element and
     * all other whitespace trimmed, and XMTML is false.
     * 
     * @return DOCUMENT ME!
     */
    public static OutputFormat createPrettyPrint() {
        OutputFormat format = new OutputFormat();
        format.setIndentSize(2);
        format.setNewlines(true);
        format.setTrimText(true);
        format.setPadText(true);

        return format;
    }

猜你喜欢

转载自blog.csdn.net/Soul_Programmer_Swh/article/details/84289948