Java中Xml和实体互转

Java中Xml和实体互转

1. 工具类 JaxbUtil

import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.namespace.QName;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import sun.awt.geom.AreaOp;

public class JaxbUtil {
    
    

    @SuppressWarnings("rawtypes")
    private static ConcurrentMap<Class, JAXBContext> jaxbContexts = new ConcurrentHashMap<Class, JAXBContext>();

    /**
     * Java Object->Xml without encoding.
     */
    @SuppressWarnings("rawtypes")
    public static String toXml(Object root) {
    
    
        Class clazz = root.getClass();
        return toXml(root, clazz, null);
    }

    /**
     * Java Object->Xml with encoding.
     */
    @SuppressWarnings("rawtypes")
    public static String toXml(Object root, String encoding) {
    
    
        Class clazz = root.getClass();
        return toXml(root, clazz, encoding);
    }

    /**
     * Java Object->Xml with encoding.
     */
    @SuppressWarnings("rawtypes")
    public static String toXml(Object root, Class clazz, String encoding) {
    
    
        try {
    
    
            StringWriter writer = new StringWriter();
            createMarshaller(clazz, encoding).marshal(root, writer);
            return writer.toString();
        } catch (JAXBException e) {
    
    
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Java Collection->Xml without encoding, 特别支持Root Element是Collection的情形.
     */
    @SuppressWarnings("rawtypes")
    public static String toXml(Collection<?> root, String rootName, Class clazz) {
    
    
        return toXml(root, rootName, clazz, null);
    }

    /**
     * Java Collection->Xml with encoding, 特别支持Root Element是Collection的情形.
     */
    @SuppressWarnings("rawtypes")
    public static String toXml(Collection<?> root, String rootName, Class clazz, String encoding) {
    
    
        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);

            return writer.toString();
        } catch (JAXBException e) {
    
    
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Xml->Java Object.
     */
    @SuppressWarnings("unchecked")
    public static <T> T fromXml(String xml, Class<T> clazz) {
    
    
        try {
    
    
            StringReader reader = new StringReader(xml);
            return (T) createUnmarshaller(clazz).unmarshal(reader);
        } catch (JAXBException e) {
    
    
            e.printStackTrace();
        }
        return null;
    }

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

            Marshaller marshaller = jaxbContext.createMarshaller();

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

            if (StringUtils.isNotBlank(encoding)) {
    
    
                marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            }
            return marshaller;
        } catch (JAXBException e) {
    
    
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建UnMarshaller.
     * 线程不安全,需要每次创建或pooling。
     */
    @SuppressWarnings("rawtypes")
    public static Unmarshaller createUnmarshaller(Class clazz) {
    
    
        try {
    
    
            JAXBContext jaxbContext = getJaxbContext(clazz);
            return jaxbContext.createUnmarshaller();
        } catch (JAXBException e) {
    
    
            e.printStackTrace();
        }
        return null;
    }

    @SuppressWarnings("rawtypes")
    protected static JAXBContext getJaxbContext(Class clazz) {
    
    
        Validate.notNull(clazz, "'clazz' must not be null");
        JAXBContext jaxbContext = jaxbContexts.get(clazz);
        if (jaxbContext == null) {
    
    
            try {
    
    
                jaxbContext = JAXBContext.newInstance(clazz, CollectionWrapper.class);
                jaxbContexts.putIfAbsent(clazz, jaxbContext);
            } catch (JAXBException ex) {
    
    
                throw new RuntimeException("Could not instantiate JAXBContext for class [" + clazz + "]: "
                        + ex.getMessage(), ex);
            }
        }
        return jaxbContext;
    }

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

        @XmlAnyElement
        protected Collection<?> collection;
    }
}


2. 实体转Xml演示

2-1 实体类,Main方法中,含实体和Xml互转的测试代码

package com.ruoyi.system.controller;


import com.alibaba.fastjson.JSON;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;


//设置生成的xml的根节点的名称
@XmlRootElement(name="sendHospitalInfo")
//设置根据字段还是方法生成
@XmlAccessorType(XmlAccessType.FIELD)
public class Hospital implements Serializable {
    
    
    //xml节点的名称
    @XmlElement(name="hospitalId")
    private String hospitalid;

    //忽略此属性
    @XmlTransient
    private long id;

    @XmlElement(name="hospitalName")
    private String hospitalname;

    public String getHospitalid() {
    
    
        return hospitalid;
    }

    public void setHospitalid(String hospitalid) {
    
    
        this.hospitalid = hospitalid;
    }

    public long getId() {
    
    
        return id;
    }

    public void setId(long id) {
    
    
        this.id = id;
    }

    public String getHospitalname() {
    
    
        return hospitalname;
    }

    public void setHospitalname(String hospitalname) {
    
    
        this.hospitalname = hospitalname;
    }

    public static void main(String[] args) {
    
    
        Hospital sydw = new Hospital();
        sydw.setHospitalid("001");
        sydw.setHospitalname("hospital_name");


        Hospital sydw2 = new Hospital();
        sydw2.setHospitalid("002");
        sydw2.setHospitalname("hospital_name");

        List<Hospital> lists = new ArrayList<>();
        lists.add(sydw);
        lists.add(sydw2);
        Demo demo = new Demo();
        demo.setHospitals(lists);
        // 实体转xml
        System.out.println(JaxbUtil.toXml(demo));
        System.out.println(JaxbUtil.toXml(sydw));

        // xml 转实体
        Demo demo1 = new Demo();
        demo1=JaxbUtil.fromXml(JaxbUtil.toXml(demo),Demo.class);
        System.out.println(JSON.toJSONString(demo1));
    }
}

@XmlRootElement(name="sendHospitalInfoList")
//设置根据字段还是方法生成
@XmlAccessorType(XmlAccessType.FIELD)
class Demo{
    
    
    private List<Hospital> hospitals;

    public List<Hospital> getHospitals() {
    
    
        return hospitals;
    }

    public void setHospitals(List<Hospital> hospitals) {
    
    
        this.hospitals = hospitals;
    }
}


2-2 生成的Xml结果

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<sendHospitalInfoList>
    <hospitals>
        <hospitalId>001</hospitalId>
        <hospitalName>hospital_name</hospitalName>
    </hospitals>
    <hospitals>
        <hospitalId>002</hospitalId>
        <hospitalName>hospital_name</hospitalName>
    </hospitals>
</sendHospitalInfoList>

<!-- 对应的Json
	{"hospitals":[{"hospitalid":"001","hospitalname":"hospital_name","id":0},
	{"hospitalid":"002","hospitalname":"hospital_name","id":0}]}
--> 

3. Java中操作Xml,可参考我写的另一篇博客【更完整、使用推荐】

猜你喜欢

转载自blog.csdn.net/qq_17847881/article/details/130281437
今日推荐