XML工具类

package com.panchan.tsmese.utils;

import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.util.StringUtils;
import org.xml.sax.InputSource;

import com.panchan.tsmese.entity.ErrorCodeEnum;
import com.panchan.tsmese.exception.TsmEseException;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description: XML工具类
 * @version 1.0
 * @since JDK1.8
 * @author
 * @Created on 2018年9月14日
 */
@Slf4j
public class FormatUtils {

    /**
     * 格式化xml字符串
     * @param str
     * @return
     */
    public static String formatXml(String str) {
        
        try {
            if(!isXmlDocument(str)){
                return str;
            }
            
            Document document = null;
            document = DocumentHelper.parseText(str);
            // 格式化输出格式
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("UTF-8");
            StringWriter writer = new StringWriter();
            // 格式化输出流
            XMLWriter xmlWriter = new XMLWriter(writer, format);
            // 将document写入到输出流
            xmlWriter.write(document);
            xmlWriter.close();

            return writer.toString();
        }catch(Exception e){
            e.printStackTrace();
            throw new TsmEseException(ErrorCodeEnum.XML_PARSE_ERROR.getErrorCode(), e);
        }
    }

    /**
     * 判断字符串是否为xml字符串
     * @param rtnMsg
     * @return
     */
    public static boolean isXmlDocument(String rtnMsg){
     
        boolean flag = true;
        try {
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
                builder.parse( new InputSource( new StringReader( rtnMsg )));
        } catch (Exception e) {
            flag = false;
        }
        
        return flag;
    }

    /**
     * object转xml
     * 
     * @param obj
     * @param clazz
     * @return
     */
    public  static <T> String objectToXml(Object obj, Class<T> clazz) {
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");// 编码格式
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);// 是否省略xml头信息,默认false
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 是否格式化生成的xml串,默认false
            Writer writer = new StringWriter();
            marshaller.marshal(obj, writer);
            return writer.toString();
        } catch (JAXBException e) {
            log.error("解析错误", e);
            throw new TsmEseException(ErrorCodeEnum.JSON_PARSE_ERROR.getErrorCode(), e);
        }

    }

    /**
     * xml转object
     * 
     * @param xmlStr
     * @param clazz
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T xmlToObject(String xmlStr, Class<T> clazz) {
        if (!StringUtils.isEmpty(xmlStr)) {
            try {
                JAXBContext context = JAXBContext.newInstance(clazz);
                Unmarshaller unmarshaller = context.createUnmarshaller();
                return (T) unmarshaller.unmarshal(new StringReader(xmlStr));// xml字符串
            } catch (JAXBException e) {
                log.error("解析错误", e);
                throw new TsmEseException(ErrorCodeEnum.XML_PARSE_ERROR.getErrorCode(), e);
            }
        } else {
            throw new TsmEseException(ErrorCodeEnum.XML_PARSE_ERROR.getErrorCode());
        }

    }

}
原文地址:https://www.cnblogs.com/huyanlon/p/10641361.html