半步多 玄玉的博客

使用JAXB读写XML文件

2013-03-19
玄玉
XML
 

简介

JAXB(Java Architecture for XML Binding)是JDK的一部分

主要用于Object和XML之间的转换(有点类似于.NET中的XML序列化)

代码示例

package com.jadyer.demo.xml;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * 使用JAXB读写XML
 * Created by 玄玉<http://jadyer.cn/> on 2013/03/17 15:25.
 */
public class JaxbXmlDemo {
    public static void main(String[] args) throws JAXBException {
        StringWriter sw = new StringWriter();
        Student stu = new Student(1, 22, "Jadyer", new Classroom(11, 2010, "软件技术班"));

        //要在JavaBean中使用@XmlRootElement注解指定XML根元素,否则Marshal或者UnMarshal都会失败
        JAXBContext jaxbContext = JAXBContext.newInstance(Student.class);

        /*
         * 将JavaBean编排为XML字符串
         */
        Marshaller marshaller = jaxbContext.createMarshaller();
        //该值默认为false,true则不会创建即头信息,即<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
        //marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        //直接输出到控制台
        //marshaller.marshal(stu, System.out);
        marshaller.marshal(stu, sw);
        System.out.println(sw.toString());

        /*
         * 将XML字符串反编排为JavaBean
         */
        Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();
        Student student = (Student)unMarshaller.unmarshal(new StringReader(sw.toString()));
        System.out.println(student.getAge());
        System.out.println(student.getName());
        System.out.println(student.getClassroom().getName());
    }
}

这是用到的两个JavaBean

package com.jadyer.demo.xml;

import javax.xml.bind.annotation.XmlRootElement;

/**
 * 要在JavaBean中使用@XmlRootElement注解指定XML根元素,否则Marshal或者UnMarshal都会失败
 * Created by 玄玉<http://jadyer.cn/> on 2016/11/26 17:40.
 */
@XmlRootElement
public class Student {
    //各属性的getter和setter方法略
    private int id;
    private int age;
    private String name;
    private Classroom classroom;
    //必须显式或隐式的提供默认的构造方法
    public Student() {}
    public Student(int id, int age, String name, Classroom classroom) {
        this.id = id;
        this.age = age;
        this.name = name;
        this.classroom = classroom;
    }
}
package com.jadyer.demo.xml;

/**
 * Created by 玄玉<http://jadyer.cn/> on 2016/11/26 17:40.
 */
public class Classroom {
    //各属性的getter和setter方法略
    private int id;
    private int grade;
    private String name;
    //这个类也必须显式或隐式的提供默认的构造方法
    public Classroom() {}
    public Classroom(int id, int grade, String name) {
        this.id = id;
        this.grade = grade;
        this.name = name;
    }
}

控制台输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><student><age>22</age><classroom><grade>2010</grade><id>11</id><name>软件技术班</name></classroom><id>1</id><name>Jadyer</name></student>
22
Jadyer
软件技术班

Comments

Content