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;
    }
}
相关推荐
在未来等你5 分钟前
互联网大厂Java求职面试:AI与大模型应用集成及云原生挑战
java·微服务·ai·kubernetes·大模型·embedding·spring ai
源码技术栈25 分钟前
SaaS基于云计算、大数据的Java云HIS平台信息化系统源码
java·大数据·云计算·云his·his系统·云医院·区域his
编程、小哥哥27 分钟前
互联网大厂Java面试:从Spring Boot到微服务架构的技术深挖
java·spring boot·redis·微服务·prometheus·面试技巧
揽你·入怀39 分钟前
数据结构:ArrayList简单实现与常见操作实例详解
java·开发语言
okok__TXF1 小时前
SpringBoot3+AI
java·人工智能·spring
AA-代码批发V哥1 小时前
Math工具类全面指南
java·开发语言·数学建模
caihuayuan53 小时前
生产模式下react项目报错minified react error #130的问题
java·大数据·spring boot·后端·课程设计
编程、小哥哥3 小时前
Java大厂面试:从Web框架到微服务技术的场景化提问与解析
java·spring boot·微服务·面试·技术栈·数据库设计·分布式系统
界面开发小八哥3 小时前
「Java EE开发指南」如何使用MyEclipse的可视化JSF编辑器设计JSP?(二)
java·ide·人工智能·java-ee·myeclipse
找不到、了4 小时前
Spring-Beans的生命周期的介绍
java·开发语言·spring