Java Object 序列化成XML以及XML反序列化成Java Object

Java Object 序列化成XML以及XML反序列化成Java Object

@import url(http://www.blogjava.net/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
package org.sl.bean;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;

public class ObjectXmlSerial {
   
    public static void main(String[] args) throws IOException{
        UserBean user = new UserBean();
        OtherUserInfoBean otherUserInfo = new OtherUserInfoBean();
       
        otherUserInfo.setAddress("汉字");
        otherUserInfo.setEmail("[email protected]");
       
        user.setName("hello");
        user.setPassword("world");
       
        user.setOtherUserInfo(otherUserInfo);
                         
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
        BufferedOutputStream bufferOut = new BufferedOutputStream(byteArrayOut);
       
        writeObjectToXML(bufferOut, user);
        byte[] bys = byteArrayOut.toByteArray();
       
        byteArrayOut.close();
        bufferOut.close();
       
       
        ByteArrayInputStream byteArrayIn = new ByteArrayInputStream(bys);
        BufferedInputStream bufferIn = new BufferedInputStream(byteArrayIn);
       
        UserBean user1 = readObjectFromXML(bufferIn);
       
        byteArrayIn.close();
        bufferIn.close();       
       
        System.out.println(user1.getName());
        System.out.println(user1.getOtherUserInfo().getAddress());
    }
   
    public static <T extends Serializable> void writeObjectToXML(OutputStream out, T obj){
        XMLEncoder xmlEncoder = null;
       
        try{
            xmlEncoder = new XMLEncoder(out);
            xmlEncoder.writeObject(obj);
        }finally{
            if(null != xmlEncoder)
                xmlEncoder.close();
        }
    }
   
    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T readObjectFromXML(InputStream in){
        T obj = null;
        XMLDecoder xmlDecoder = null;
       
        try{
            xmlDecoder = new XMLDecoder(in);
            obj = (T) xmlDecoder.readObject();
        }finally{
            if(null != xmlDecoder)
                xmlDecoder.close();
        }
        return obj;
    }
}


Kyle Wang

你可能感兴趣的:(Java Object 序列化成XML以及XML反序列化成Java Object)