使用JAXB完成Java和XML的相互转化:
java-->xml:编排,marshal
xml-->java:反编排,unmarshal
package org.itat.xml;
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;
public class TestJaxb {
/**
* marshal编排,java-->xml
*/
@Test
public void test01() {
try {
//1.创建JAXBContext实例
JAXBContext ctx = JAXBContext.newInstance(Student.class);
//2.创建marshaller实例
Marshaller marshaller = ctx.createMarshaller();
//3.创建student对象,并将该对象转换为xml
Student student = new Student(1, "姚双双", 25, new Classroom(1, "08计算机应用技术", 2008));
//4.将java-->xml,并输出
marshaller.marshal(student, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
/*
* 运行结果:
* <?xml version="1.0" encoding="UTF-8" standalone="yes"?><student><age>25</age><classroom><grade>2008</grade><id>1</id><name>08计算机应用技术</name></classroom><id>1</id><name>姚双双</name></student>
*/
/**
* unmarshal反编排,xml-->java
*/
@Test
public void test02() {
try {
//要转换的xml
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><student><age>25</age><classroom><grade>2008</grade><id>1</id><name>08计算机应用技术</name></classroom><id>1</id><name>姚双双</name></student>";
//1.创建JAXBContext实例
JAXBContext ctx = JAXBContext.newInstance(Student.class);
//2.创建unmarshaller实例
Unmarshaller um = ctx.createUnmarshaller();
//3.读入xml,并将xml-->java
Student student = (Student)um.unmarshal(new StringReader(xml));
//4.输出
System.out.println(student.getName() + ", " + student.getClassroom().getName());
} catch (JAXBException e) {
e.printStackTrace();
}
}
/*
* 运行结果:姚双双, 08计算机应用技术
*
*/
}