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的互转操作。