java 通过JAXB 实现对象和xml互相转化

来源:互联网 发布:玉兰与木兰知乎 编辑:程序博客网 时间:2024/06/16 21:00

JAXB的话是java1.5之后出现的,对于java对象和xml文件之间互相转化的操作比较方便,以下先记录下来,免得以后忘了。

要转化成xml文件的对象:

package utils;import java.io.File;import java.util.List;import javax.xml.bind.JAXB;import javax.xml.bind.JAXBException;public class Test {private int i;private String s;private boolean b;private List<Integer> list;public int getI() {return i;}public void setI(int i) {this.i = i;}public String getS() {return s;}public void setS(String s) {this.s = s;}public boolean isB() {return b;}public void setB(boolean b) {this.b = b;}public List<Integer> getList() {return list;}public void setList(List<Integer> list) {this.list = list;}        //把xml文件转化成对象public static Test JAXBunmarshal(File xmlFile) throws JAXBException {return JAXB.unmarshal(xmlFile, Test.class);}        //把对象转化成xmlpublic void JAXBmarshal(File fRootDir) {if (!fRootDir.exists()) {fRootDir.mkdirs();} JAXB.marshal(this, new File(fRootDir, this.getS() + ".xml"));}}

主要的是JAXBunmarshal方法和JAXBmarshal方法。


测试类:

package utils;import java.io.File;import java.io.FileNotFoundException;import java.util.ArrayList;import java.util.List;import javax.xml.bind.JAXBException;public class JAXBTest {public static void main(String[] args) throws FileNotFoundException, JAXBException {List<Integer> testList;{Test test = new Test();test.setB(true);test.setI(5);test.setS("wo");testList = new ArrayList<Integer>();for (int i = 0; i < 3; i++) {testList.add(i);}test.setList(testList);//把test类转化成xml文件,当然也可以指定成outputstream,writer,string,可以参考APItest.JAXBmarshal(new File("c://"));}System.out.println("=================================");{//把xml文件转换成test类Test test = Test.JAXBunmarshal(new File("c://wo1.xml"));System.out.println(test.getI());System.out.println(test.getS());for (int i = 0; i < test.getList().size(); i++) {System.out.println(test.getList().get(i));}}}}