您的位置:首页 > 编程语言 > Java开发

JavaEE学习之JAXB

2014-04-10 11:15 246 查看

一、前言

JAXB——Java Architecture for XML Binding,是一项可以根据XML Schema产生Java类的技术。JAXB提供将XML实例文档反向生成Java对象树的方法,也能将Java对象树的内容重新写到XML实例文档。

二、JAXB相关的class和interface

(1)JAXBContext。 JAXBContext类提供到 JAXB API 的客户端入口点。它提供了管理实现 JAXB 绑定框架操作所需的 XML/Java 绑定信息的抽象,这些操作包括:解组(Unmarshaller )、编组(Marshaller)和验证(Validator)。通常使用
JAXBContext.newInstance(XXX.class)
来获取JAXBContext实例(Student是我定义的一个Entity)。

JAXBContext ctx = JAXBContext.newInstance(Student.class)


(2)Unmarshaller。 Unmarshaller 是一个Interface,它管理将 XML 数据反序列化为新创建的 Java 内容树的过程,并可在解组时有选择地验证 XML 数据。它针对如File,InputStream,URL,StringBuffer等各种不同的输入种类,提供各种重载的 unmarshal 方法。unmarshal 方法从不返回 null。如果unmarshal无法将 XML 内容的根解组到 JAXB 映射对象,则抛出 JAXBException。

Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Student stu = (Student) unmarshaller.unmarshal(file);


(3)Marshaller
Marshaller
使客户端应用程序能够将 Java 内容树转换回 XML 数据。它提供了各种重载的marshal方法。默认情况下,在将 XML 数据生成到 java.io.OutputStream 或 java.io.Writer 中时,Marshaller 将使用 UTF-8 编码。

Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 格式化输出
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// 设置输出编码,默认为UTF-8
marshaller.marshal(stu, xmlFile);


三、JAXB相关Annotation

(1)@XmlRootElement,将Java类或枚举类型映射到XML元素;

(2)@XmlElement,将Java类的一个属性映射到与属性同名的一个XML元素;

(3)@XmlAttribute,将Java类的一个属性映射到与属性同名的一个XML属性;

注意事项

(1)对于要序列化(marshal)为XML的Java类,绝不能把成员变量声明为public,否则运行将抛出异常

  com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException

(2)注解不能直接放在成员变量上,可以放在成员变量的getter或setter方法上,任选其一,否则也会抛出IllegalAnnotationsException异常

四、示例

(1)定义一个Student

package cn.com.infosky.Jaxb;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="Root")
public class Student implements Serializable {
/**
*
*/
private static final long serialVersionUID = -8317239764136972094L;

private String name;

private String country;

private String birthDate;

/**
* @return the name
*/
public String getName() {
return name;
}

/**
* @param name
*            the name to set
*/
public void setName(String name) {
this.name = name;
}

/**
* @return the country
*/
public String getCountry() {
return country;
}

/**
* @param country
*            the country to set
*/
public void setCountry(String country) {
this.country = country;
}

/**
* @return the birthDate
*/
public String getBirthDate() {
return birthDate;
}

/**
* @param birthDate the birthDate to set
*/
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
}


(2)通过Marshaller接口将Student对象序列化到TestJaxb.xml文件

public void Obj2Xml()  {
File xmlFile = new File("C:/TestJaxb.xml");
JAXBContext ctx;
try {

ctx = JAXBContext.newInstance(Student.class);

Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 格式化输出
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// 设置输出编码,默认为UTF-8

Student stu = new Student();
stu.setName("Zhangsan");
stu.setCountry("CN");

//指定时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
stu.setBirthDate(sdf.format(new Date()));
marshaller.marshal(stu, xmlFile);
System.out.println("Obj2Xml Over!");

} catch (JAXBException e) {
System.out.println("error");

System.out.println(e.toString());
System.out.println(e.getStackTrace());
// TODO: handle exception
}
}


运行后生成的TestJaxb.xml结构:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Root xmlns="http://www.example.org/wzhang">
<birthDate>2014-04-10</birthDate>
<country>CN</country>
<name>Zhangsan</name>
</Root>


(3)通过Unmarshaller接口从XML文件中获取Student对象

	public void XmlToObj() {

try {

File file = new File("C:\\TestJaxb.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Student.class);

Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Student stu = (Student) unmarshaller.unmarshal(file);
System.out.println(stu.getName()+"..."+stu.getBirthDate());

} catch (JAXBException e) {
e.printStackTrace();
}
}


(4)测试代码

public static void main(String[] args) {
new App().Obj2Xml();
//new App().XmlToObj();
}


示例源代码下载,猛戳JaxbDemo.7z
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: