首页 > 编程语言 > 详细

Java XMl序列化与反序列化

时间:2015-02-11 11:05:09      阅读:261      评论:0      收藏:0      [点我收藏+]

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;

public class XmlUtil {


    /**
     * 序列化XML
     * @param object
     * @return
     * @throws JAXBException
     * @throws UnsupportedEncodingException
     */
    public static String Marshal(Object object) throws JAXBException, UnsupportedEncodingException
    {
        JAXBContext context = JAXBContext.newInstance(object.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");        //编码格式
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);   //格式化XML

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        marshaller.marshal(object, outputStream);

        return outputStream.toString("UTF-8");
    }

    /**
     * 反序列化XML
     * @param cls
     * @param objStr
     * @param <T>
     * @return
     * @throws JAXBException
     * @throws UnsupportedEncodingException
     */
    public static <T> T UnMarshal(Class cls, String objStr) throws JAXBException, UnsupportedEncodingException
    {
        JAXBContext context = JAXBContext.newInstance(cls);
        Unmarshaller unMarshaller = context.createUnmarshaller();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(objStr.getBytes("UTF-8"));
        return (T)unMarshaller.unmarshal(inputStream);
    }
}

Java XMl序列化与反序列化

原文:http://my.oschina.net/liyan2013/blog/377560

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!