使用jaxb將對象和xml進行互轉

jaxb是java自帶的包中。話不多說,以例子爲基準

import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;


public class Test {
/**
* 編排
*/
@org.junit.Test
public void test01(){
try {
JAXBContext jc = JAXBContext.newInstance(Student.class);
Marshaller marshaller= jc.createMarshaller();
marshaller.marshal(new Student(22, "張三", new ClassRoom(2014,"計算機")), System.out);

} catch (JAXBException e) {
e.printStackTrace();
}
}

/**
* 反編排
* @throws JAXBException 
*/
@org.junit.Test
public void test02() throws JAXBException{
String str="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><student><id>22</id><name>張三</name><room><grade>2014</grade><name>計算機</name></room></student>";
JAXBContext jc=JAXBContext.newInstance(Student.class);
Unmarshaller unmarshaller=jc.createUnmarshaller();
Student stu=(Student) unmarshaller.unmarshal(new StringReader(str));
System.out.println(stu.getName()+","+stu.getRoom().getName());
}


以上兩個方法實現了,java對象和xml的互轉操作。


發佈了46 篇原創文章 · 獲贊 3 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章