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);
- }
- //把对象转化成xml
- public 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,可以参考API
- test.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));
- }
- }
- }
- }