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;
    }

}
相关推荐
空谷忧人30 分钟前
【SpringMVC】详细介绍SpringMVC的执行流程
java·后端·mvc·springmvc
攒了一袋星辰32 分钟前
java -- SpringMVC表现层数据封装详解
java·开发语言·python
武子康36 分钟前
大数据-67 Kafka 高级特性 分区 分配策略 Ranger、RoundRobin、Sticky、自定义分区器
java·大数据·分布式·架构·kafka
LiberInfo1 小时前
Docker + Nacos + Spring Cloud Gateway 实现简单的动态路由配置修改和动态路由发现
java·spring boot·spring cloud·docker·nacos·gateway·动态路由
镜中的女孩-potato2 小时前
关于uniapp的vue2.x版本的路由守卫拦截方案
前端·vue.js·uni-app
罗曼蒂克在消亡3 小时前
拦截器和过滤器
java·servlet
恰小面包3 小时前
uniapp获取地理位置的API
前端·小程序·uni-app
天上掉下来个程小白3 小时前
HTML-04.新浪新闻-标题-超链接
前端·html
茉么乔4 小时前
java excel poi导出 支持多表头的公共导出方法
java·excel·poi
AskHarries4 小时前
Spring Boot集成protobuf快速入门Demo
java·spring boot·后端·protobuf