Java XMl序列化与反序列化


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,反序列化,序列化)