JAXB 实现JavaBean与xml互转(一)

来源:互联网 发布:化学反应速率实验数据 编辑:程序博客网 时间:2024/06/05 07:37

一、介绍

  JAXB,Java Architecture for XML Binding, 是一个业界的标准,即是一项可以根据XML Schema产生Java类的技术。该过程中,JAXB也提供了将XML实例文档反向生成Java对象树的方法,并能将Java对象树的内容重新写到XML实例文档。

  EJBWeb Services应用过程中就可以通过注解的形式将xml和javabean之间相互转换已快速开发。

二、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)UnmarshallerUnmarshaller 是一个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)MarshallerMarshaller使客户端应用程序能够将 Java 内容树转换回 XML 数据。它提供了各种重载的marshal方法。默认情况下,在将 XML 数据生成到java.io.OutputStreamjava.io.Writer 中时,Marshaller 将使用 UTF-8 编码。

Marshaller marshaller = ctx.createMarshaller();marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 格式化输出marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// 设置输出编码,默认为UTF-8marshaller.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-8Student 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());}}

 

运行后生成的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();}



五、总结

  和ORM一样,XML和Object之间的转换可以称为OXM,Object XML Mapping的缩写,java对象映射成XML数据,或者将XML数据映射成java对象。最终都以面向对象的形式优化我们的开发。

1 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 糖猫电话手表关机了找不到了怎么办 小天才电话手表被洗衣机洗了怎么办 小天才电话手表放洗衣机洗了怎么办 小天才电话手表泡水了怎么办 小天才电话手表联不上网怎么办 肺炎用激素治疗后肚子大了怎么办 8岁以下儿童总是低烧不退怎么办? 微博里面的视频不能改变方向怎么办 朗逸导航倒车一体机死机了怎么办 乐淘乐电话手表的二维码没了怎么办 艾蔻儿童手表二维码丢了怎么办 糖猫儿童智能手表二维码丢了怎么办 海信电视用遥控器关了打不开怎么办 创维4k电视遥控器按键坏了怎么办 大疆3s云台陀螺仪错误怎么办 无线路由我用手机上网网速慢怎么办 下载的软件安装包以丢失怎么办 战舰世界航母的飞机恐惧状态怎么办 cad打开图纸不显示轴号怎么办 若背包忘在服务区没拿怎么办 使劲擤鼻涕耳朵耳朵疼了怎么办 用力擤鼻涕一侧的脸肿了怎么办 擦鼻涕太用力耳朵塞住了怎么办 宝宝鼻腔里有鼻涕呼呼响怎么办 黏痰在嗓子眼很干出不来怎么办 宝宝生病好了不久突然又咳嗽怎么办 7个月的宝宝经常生病怎么办 擤鼻涕鼻子周围红肿爆皮怎么办 洗衣机有鼻涕虫洗过的衣服怎么办 手机丢了里边有穿内衣照片怎么办 脸上不知是过敏还是湿疹流水怎么办 一个月的宝宝鼻子不通气怎么办 六个月的宝宝有清水鼻涕怎么办 一岁三个月宝宝流清鼻涕怎么办 宝宝流清水鼻涕怎么办最简单方法 8个月宝宝流清鼻涕怎么办 7个月宝宝流清鼻涕怎么办 9个月宝宝流清鼻涕怎么办 十一个月宝宝流清鼻涕怎么办 18个月宝宝咳嗽有痰怎么办 2个月宝宝鼻子不通气怎么办