本例介紹如何將一個對象輸出到XML文檔,再從XML文檔中讀取到內存,把一個描述學生的對象輸出到XML文檔,然后從XML文檔中讀取學生信息到內存。
java.beans.XMLEncoder是XML編碼器,它的writeObject方法能把對象以XML的格式輸出到文件中。
java.beans.XMLDecoder是XML解碼器,它的readObject方法能把XML文檔的內容讀到對象中。注意,它只能解碼用XMLEncoder生成的XML文檔。
XMLEncoder和XMLDecoder相當于對象的序列化和反序列化,只不過它以XML的格式序列化對象。

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
* 根據對象生成XML文檔.
* 使用Java提供的java.beans.XMLEncoder和java.beans.XMLDecoder類。
* 這是JDK 1.4以后才出現的類
*/
public class Object2XML {

/**
* 對象輸出到XML文件
* @param obj 待輸出的對象
* @param outFileName 目標XML文件的文件名
* @return 返回輸出XML文件的路徑
* @throws FileNotFoundException
*/
public static String object2XML(Object obj, String outFileName)
throws FileNotFoundException {
// 構造輸出XML文件的字節輸出流
File outFile = new File(outFileName);
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(outFile));
// 構造一個XML編碼器
XMLEncoder xmlEncoder = new XMLEncoder(bos);
// 使用XML編碼器寫對象
xmlEncoder.writeObject(obj);
// 關閉編碼器
xmlEncoder.close();
return outFile.getAbsolutePath();
}

/**
* 把XML文件解碼成對象
* @param inFileName 輸入的XML文件
* @return 返回生成的對象
* @throws FileNotFoundException
*/
public static Object xml2Object(String inFileName)
throws FileNotFoundException {
// 構造輸入的XML文件的字節輸入流
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(inFileName));
// 構造一個XML解碼器
XMLDecoder xmlDecoder = new XMLDecoder(bis);
// 使用XML解碼器讀對象
Object obj = xmlDecoder.readObject();
// 關閉解碼器
xmlDecoder.close();
return obj;
}

public static void main(String[] args) throws IOException {

// 構造一個StudentBean對象
StudentBean student = new StudentBean();
student.setName("wamgwu");
student.setGender("male");
student.setAge(15);
student.setPhone("55556666");
// 將StudentBean對象寫到XML文件
String fileName = "AStudent.xml";
Object2XML.object2XML(student, fileName);
// 從XML文件讀StudentBean對象
StudentBean aStudent = (StudentBean)Object2XML.xml2Object(fileName);
// 輸出讀到的對象
System.out.println(aStudent.toString());
}
}



















































































-- 學海無涯