使用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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章