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

Java XMl序列化与反序列化

时间:2015-02-11 11:06:22      阅读:217      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!