码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA实体XML相互转换

时间:2015-03-17 09:02:33      阅读:397      评论:0      收藏:0      [点我收藏+]

标签:

package com.jiayu.his.util;

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;

/**
 * 使用Jaxb2.0实现XML<->Java Object的Mapper.
 * 在创建时需要设定所有需要序列化的Root对象的Class.
 * 特别支持Root对象是Collection的情形.
 */
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 = Reflections.getUserClass(root);
        return toXml(root, clazz, null);
    }

    /**
     * Java Object->Xml with encoding.
     */
    @SuppressWarnings("rawtypes")
    public static String toXml(Object root, String encoding) {
        Class clazz = Reflections.getUserClass(root);
        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) {
            throw Exceptions.unchecked(e);
        }
    }

    /**
     * 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) {
            throw Exceptions.unchecked(e);
        }
    }

    /**
     * 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) {
            throw Exceptions.unchecked(e);
        }
    }

    /**
     * 创建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) {
            throw Exceptions.unchecked(e);
        }
    }

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

    @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;
    }
}
package com.jiayu.his.biz.yygh.entity;

import java.io.Serializable;

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;

import com.jiayu.his.base.Page;
import com.jiayu.his.util.JaxbUtil;

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

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

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

    @XmlElement(name="tel")
    private String tel;

    @XmlElement(name="webite")
    private String website;

    @XmlElement(name="hospLevel")
    private String hosplevel;

    @XmlElement(name="hospArea")
    private String hosparea;

    @XmlElement(name="desc")
    private String yyjj;

    @XmlElement(name="maxRegDays")
    private String maxregdays;

    @XmlElement(name="startRegTime")
    private String startregtime;

    @XmlElement(name="stopRegTime")
    private String stopregtime;

    @XmlElement(name="scbz")
    private String scbz;

    @XmlElement(name="yl")
    private String yl;

    @XmlTransient
    private Page page;

    @XmlTransient
    private String deptid;
    
    @XmlTransient
    private String deptname;
    
    @XmlTransient
    private String parentId;
    
    @XmlTransient
    private String ksjj;
    
    public Page getPage() {
        return page;
    }

    public void setPage(Page page) {
        this.page = page;
    }
    public String getHospitalid() {
        return hospitalid;
    }

    public void setHospitalid(String hospitalid) {
        this.hospitalid = hospitalid == null ? null : hospitalid.trim();
    }
    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 == null ? null : hospitalname.trim();
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr == null ? null : addr.trim();
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel == null ? null : tel.trim();
    }

    public String getWebsite() {
        return website;
    }

    public void setWebsite(String website) {
        this.website = website == null ? null : website.trim();
    }

    public String getHosplevel() {
        return hosplevel;
    }

    public void setHosplevel(String hosplevel) {
        this.hosplevel = hosplevel == null ? null : hosplevel.trim();
    }

    public String getHosparea() {
        return hosparea;
    }

    public void setHosparea(String hosparea) {
        this.hosparea = hosparea == null ? null : hosparea.trim();
    }  

    public String getYyjj() {
        return yyjj;
    }

    public void setYyjj(String yyjj) {
        this.yyjj = yyjj;
    }

    public String getMaxregdays() {
        return maxregdays;
    }

    public void setMaxregdays(String maxregdays) {
        this.maxregdays = maxregdays == null ? null : maxregdays.trim();
    }

    public String getStartregtime() {
        return startregtime;
    }

    public void setStartregtime(String startregtime) {
        this.startregtime = startregtime == null ? null : startregtime.trim();
    }

    public String getStopregtime() {
        return stopregtime;
    }

    public void setStopregtime(String stopregtime) {
        this.stopregtime = stopregtime == null ? null : stopregtime.trim();
    }

    public String getScbz() {
        return scbz;
    }

    public void setScbz(String scbz) {
        this.scbz = scbz == null ? null : scbz.trim();
    }

    public String getYl() {
        return yl;
    }

    public void setYl(String yl) {
        this.yl = yl == null ? null : yl.trim();
    }

    public String getDeptid() {
        return deptid;
    }

    public void setDeptid(String deptid) {
        this.deptid = deptid;
    }

    public String getDeptname() {
        return deptname;
    }

    public void setDeptname(String deptname) {
        this.deptname = deptname;
    }

    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    public String getKsjj() {
        return ksjj;
    }

    public void setKsjj(String ksjj) {
        this.ksjj = ksjj;
    }
    
    public static void main(String[] args) {
        YwYyghSydw sydw = new YwYyghSydw();
        sydw.setHospitalid("001");
        sydw.setHospitalname("11");
        sydw.setAddr("dfffffffffffffffff");
        sydw.setTel("111111111");
        System.out.println(JaxbUtil.toXml(sydw));
        String xml=JaxbUtil.toXml(sydw);
        YwYyghSydw sydw1 = new YwYyghSydw();
        sydw1=JaxbUtil.fromXml(xml,YwYyghSydw.class);
        System.out.println(JaxbUtil.toXml(sydw1));
    }
}

 

JAVA实体XML相互转换

标签:

原文地址:http://www.cnblogs.com/liuhaixu/p/4343479.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!