package com.brilliance.isc.doc.utils;


import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.StringWriter;

/**
 * xml转换处理
 */
public class XmlTransformerUtil {

    /**
     * 格式化xml
     * @param xmlStr
     * @return
     */
    public static String prettyFormat(String xmlStr) {
        if (StringUtils.isBlank(xmlStr)) {
            return xmlStr;
        }
        StringWriter outputWriter = new StringWriter();
        try {
            Document document = DocumentHelper.parseText(xmlStr);
            // 设置格式化参数
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setExpandEmptyElements(true); // 设置为空的元素采用起始和结束标签
            XMLWriter writer = new XMLWriter(outputWriter, format);
            writer.write(document);
        } catch (Exception e) {
            return xmlStr;
        }
        return outputWriter.toString();
    }
}