源代碼下載下傳:連結: http://pan.baidu.com/s/1ntL1a7R password: rwp1
本文主要講述:使用jaxb完畢對象和xml之間的轉換
TestJava2xml.java例如以下所看到的:
package com.tgb.jaxb.v1;
import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.junit.Test;
/**
* 通過Java和XML之間互相轉換
* @author 趙栗婧
* @version 1.0.0 , 2015年6月25日 下午12:12:16
*/
public class TestJava2xml {
// 測試:Java檔案轉化為Xml檔案
@Test
public void testJava2Xml() {
try {
JAXBContext ctx = JAXBContext.newInstance(Student.class);
// 用于Java檔案轉化為Xml檔案的類
Marshaller marshaller = ctx.createMarshaller();
Student student = new Student(1001, "趙栗婧", 20, new Classroom(10,
"10級生命科學與project", 2010));
marshaller.marshal(student, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
// 測試Xml檔案轉化為Java檔案
@Test
public void testXml2Java() {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<student>"
+ "<age>20</age>"
+ "<classroom>"
+ "<grade>2010</grade>"
+ "<id>10</id>"
+ "<name>10級生命科學與project</name>"
+ "</classroom>"
+ "<id>1001</id>"
+ "<name>趙栗婧</name>"
+ "</student>";
try {
JAXBContext ctx = JAXBContext.newInstance(Student.class);
// 用于Xml檔案轉化為Java檔案的類
Unmarshaller um = ctx.createUnmarshaller();
Student student = (Student) um.unmarshal(new StringReader(xml));
System.out.println(student.getName() + ","
+ student.getClassroom().getName());
} catch (JAXBException e) {
e.printStackTrace();
}
}
}