xml 工具类

复制代码
package com.sunac.ocims.entity.esb;

import jdk.internal.org.xml.sax.SAXException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import java.io.*;

public class XmlUtils {
    private static final Logger log = LoggerFactory.getLogger(XmlUtils.class);

    public static String convertToXml(Object obj) {
        String resultXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n";
        return resultXml + convertToXml(obj, "utf-8");
    }

    public static String convertToXml(Object obj, String encoding) {
        String result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            result = writer.toString();
        } catch (Exception e) {
            log.error("转换XML失败:" + e.getMessage());
        }
        return result;
    }

    /**
     * 将对象根据路径转换成xml文件
     *
     * @param obj
     * @param path
     * @return
     */
    public static void convertToXmlFile(Object obj, String path) {
        try {
            // 利用jdk中自带的转换类实现
            JAXBContext context = JAXBContext.newInstance(obj.getClass());

            Marshaller marshaller = context.createMarshaller();
            // 格式化xml输出的格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
                    Boolean.TRUE);
            // 将对象转换成输出流形式的xml
            // 创建输出流
            FileWriter fw = null;
            try {
                fw = new FileWriter(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
            marshaller.marshal(obj, fw);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    /**
     * 将String类型的xml转换成对象
     */
    public static <V> V convertXmlStrToObject(Class<V>  clazz, String xmlStr) {
        String resultXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n";
        V xmlObject = null;
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            // 进行将Xml转成对象的核心接口
            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader sr = new StringReader(resultXml + xmlStr);
            xmlObject = (V)unmarshaller.unmarshal(sr);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return xmlObject;
    }

    @SuppressWarnings("unchecked")
    /**
     * 将file类型的xml转换成对象
     */
    public static Object convertXmlFileToObject(Class clazz, String xmlPath) {
        Object xmlObject = null;
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            FileReader fr = null;
            try {
                fr = new FileReader(xmlPath);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            xmlObject = unmarshaller.unmarshal(fr);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return xmlObject;
    }

    /**
     * xml装换成JavaBean
     *
     * @param t
     * @param xml
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T converyToJavaBean(Class<T> t, String xml) {
        // 如果xml参数中有以下协议,则不需要再重复加
        String resultXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n";
        T obj = null;
        SAXParserFactory sax = null;
        StringReader reader = null;
        try {
            JAXBContext context = JAXBContext.newInstance(t);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            reader = new StringReader(resultXml + xml);
            sax = SAXParserFactory.newInstance();
//            sax.setXIncludeAware(false);
            sax.setValidating(false);
            // 忽略命名空间
            sax.setNamespaceAware(false);
            XMLReader xmlReader = sax.newSAXParser().getXMLReader();
            Source source = new SAXSource(xmlReader, new InputSource(reader));
            obj = (T) unmarshaller.unmarshal(source);
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }

    /**
     * xml文件配置转换为对象
     * @param xmlPath  xml文件路径
     * @param load    java对象.Class
     * @return    java对象
     * @throws JAXBException
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public static <T> T xmlToBean(String xmlPath, Class<T> load) throws Exception {
        JAXBContext context = JAXBContext.newInstance(load);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        SAXSource saxSource = newSAxSource(xmlPath);
        return (T) unmarshaller.unmarshal(saxSource);
    }

    protected static SAXSource newSAxSource(String  xml) throws FileNotFoundException, ParserConfigurationException, SAXException, org.xml.sax.SAXException {
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        saxParserFactory.setNamespaceAware(false);
        XMLReader xmlReader = saxParserFactory.newSAXParser().getXMLReader();
        SAXSource saxSource = new SAXSource(xmlReader, new InputSource(new ByteArrayInputStream(xml.getBytes())));
        return saxSource;
    }

}
相关推荐
科技探秘人10 分钟前
Chrome与火狐哪个浏览器的隐私追踪功能更好
前端·chrome
科技探秘人11 分钟前
Chrome与傲游浏览器性能与功能的深度对比
前端·chrome
JerryXZR16 分钟前
前端开发中ES6的技术细节二
前端·javascript·es6
七星静香18 分钟前
laravel chunkById 分块查询 使用时的问题
java·前端·laravel
Jacob程序员19 分钟前
java导出word文件(手绘)
java·开发语言·word
ZHOUPUYU19 分钟前
IntelliJ IDEA超详细下载安装教程(附安装包)
java·ide·intellij-idea
q24985969321 分钟前
前端预览word、excel、ppt
前端·word·excel
stewie623 分钟前
在IDEA中使用Git
java·git
小华同学ai26 分钟前
wflow-web:开源啦 ,高仿钉钉、飞书、企业微信的审批流程设计器,轻松打造属于你的工作流设计器
前端·钉钉·飞书
Gavin_91535 分钟前
【JavaScript】模块化开发
前端·javascript·vue.js