使用JAXB处理JavaBean和XML的转换

package com.jadyer.jaxb;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * 使用JAXB处理JavaBean和XML的转换
 * @create Mar 17, 2013 3:25:49 PM
 * @author 玄玉<http://blog.csdn/net/jadyer>
 */
public class TestJAXB {
	public static void main(String[] args) throws JAXBException {
		StringWriter sw = new StringWriter();
		Student stu = new Student(1, 22, "Jadyer", new Classroom(11, 2010, "软件技术班"));
		/**
		 * 生成JAXBContext
		 */
		//要在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());
	}
}


下面是用到的两个实体类

package com.jadyer.jaxb;

import javax.xml.bind.annotation.XmlRootElement;

/**
 * 必须显式或隐式的提供默认的构造方法
 */
@XmlRootElement
public class Student {
	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;
	}
}
/**
 * 各属性的getter和setter方法略
 */
public class Classroom {
	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,JAXB,marshal,xml解析,unmarshal)