xml解析工具类

java 复制代码
package com.yannis.utils;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.namespace.QName;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class JaxbMapper {

    private static ConcurrentMap<Class, JAXBContext> jaxbContexts = new ConcurrentHashMap<Class, JAXBContext>();

    public static String toXml(Object root) {
        return toXml(root, root.getClass(), null);
    }

    public static String toXml(Object root, String encoding) {
        return toXml(root, root.getClass(), encoding);
    }

//    @SneakyThrows(JAXBException.class)
    public static String toXml(Object root, Class clazz, String encoding){
        String s = "";
        try {
            StringWriter writer = new StringWriter();
            createMarshaller(clazz, encoding).marshal(root, writer);
            s = writer.toString();
        } catch (Exception e) {

        }
     return s;
    }

    public static String toXml(Collection<?> root, String rootName, Class clazz) {
        return toXml(root, rootName, clazz, null);
    }

    public static String toXml(Collection<?> root, String rootName, Class clazz, String encoding) {
        String string = "";
        try {
            CollectionWrapper wrapper = new CollectionWrapper();
            wrapper.collection = root;

            JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>(new QName(rootName),
                    CollectionWrapper.class, wrapper);

            StringWriter writer = new StringWriter();
            createMarshaller(clazz, encoding).marshal(wrapperElement, writer);

            string =  writer.toString();
        } catch (Exception e) {

        }
      return string;
    }

    @SuppressWarnings("unchecked")
    public static <T> T fromXml(String xml, Class<T> clazz) throws Exception{
        StringReader reader = new StringReader(xml);
        return (T) createUnmarshaller(clazz).unmarshal(reader);
    }

    /**
     * 创建Marshaller并设定encoding(可为null).
     * 线程不安全,需要每次创建或pooling。
     */
    public static Marshaller createMarshaller(Class clazz, String encoding) throws Exception{
        JAXBContext jaxbContext = getJaxbContext(clazz);

        Marshaller marshaller = jaxbContext.createMarshaller();

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        if (encoding != null) {
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
        }

        return marshaller;
    }

    /**
     * 创建UnMarshaller.
     * 线程不安全,需要每次创建或pooling。
     */
    public static Unmarshaller createUnmarshaller(Class clazz) throws Exception{
        JAXBContext jaxbContext = getJaxbContext(clazz);
        return jaxbContext.createUnmarshaller();
    }

    protected static JAXBContext getJaxbContext(Class clazz) throws Exception{
//		Assert.notNull(clazz, "'clazz' must not be null");
        JAXBContext jaxbContext = jaxbContexts.get(clazz);
        if (jaxbContext == null) {
            jaxbContext = JAXBContext.newInstance(clazz, CollectionWrapper.class);
            jaxbContexts.putIfAbsent(clazz, jaxbContext);
        }
        return jaxbContext;
    }

    /**
     * 封装Root Element 是 Collection的情况.
     */
    public static class CollectionWrapper {

        @XmlAnyElement
        protected Collection<?> collection;
    }
}
相关推荐
stein_java36 分钟前
springMVC-10验证及国际化
java·spring
weixin_4786897639 分钟前
C++ 对 C 的兼容性
java·c语言·c++
LUCIAZZZ1 小时前
HikariCP数据库连接池原理解析
java·jvm·数据库·spring·springboot·线程池·连接池
sky_ph2 小时前
JAVA-GC浅析(二)G1(Garbage First)回收器
java·后端
IDRSolutions_CN2 小时前
PDF 转 HTML5 —— HTML5 填充图形不支持 Even-Odd 奇偶规则?(第二部分)
java·经验分享·pdf·软件工程·团队开发
hello早上好2 小时前
Spring不同类型的ApplicationContext的创建方式
java·后端·架构
HelloWord~3 小时前
SpringSecurity+vue通用权限系统2
java·vue.js
让我上个超影吧3 小时前
黑马点评【基于redis实现共享session登录】
java·redis
BillKu4 小时前
Java + Spring Boot + Mybatis 插入数据后,获取自增 id 的方法
java·tomcat·mybatis
全栈凯哥4 小时前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表