JAXB(Java Architecture for XML Binding)是JDK的一部分,用于Object <-> XML的转换(有点类似于.NET中的XML序列化)。

1、创建XSD

可以使用任何工具生成XSD工具,比如XMLSPY。eclipse也提供了相关的jaxb插件,File -> New -> XML Schema File

文件命名为order.xsd,eclipse中也提供了xsd可视化编辑工具

当然,你要是很NB,对xsd结构倒背如流的话,完全也可以纯手写。

 <?xml version="1.0" encoding="UTF-8"?>
<!-- edited with XMLSpy v2013 (http://www.altova.com) by () -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:element name="Order">
<xs:annotation>
<xs:documentation>Comment describing your root element</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element name="OrderNo" type="xs:string"/>
<xs:element name="OrderDateTime" type="xs:dateTime"/>
<xs:element name="CustomerName" type="xs:string"/>
<xs:element name="OrderItems">
<xs:complexType>
<xs:sequence>
<xs:element name="Produdct" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="ProductNo" type="xs:string"/>
<xs:element name="ProductName" type="xs:string"/>
<xs:element name="Price" type="xs:float"/>
<xs:element name="Amount" type="xs:int"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

Order.xsd

上面是Order.xsd的内容

2、根据XSD生成示例Xml

在XSD文件上右击 -> Generate -> XmlFile

会弹出一个框:

Prefix这里,如果不需要,可以参考上图自行清空,如果一些可选节点也需要生成示例数据,上图中的Create optional attributes、Create optional elements这二项也勾选上。

生成的order.xml内容如下:

 <?xml version="1.0" encoding="UTF-8"?>
<!--Sample XML file generated by XMLSpy v2013 (http://www.altova.com)-->
<Order xsi:noNamespaceSchemaLocation="order.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<OrderNo>0000001</OrderNo>
<OrderDateTime>2001-12-17T09:30:47Z</OrderDateTime>
<CustomerName>jimmy</CustomerName>
<OrderItems>
<Produdct>
<ProductNo>P-01</ProductNo>
<ProductName>Book</ProductName>
<Price>1.14159E0</Price>
<Amount>1</Amount>
</Produdct>
<Produdct>
<ProductNo>P-02</ProductNo>
<ProductName>iPhone 5C</ProductName>
<Price>3.14159E0</Price>
<Amount>2</Amount>
</Produdct>
</OrderItems>
</Order>

Order.xml

3、根据xsd生成java类

同样在xsd上右击 -> Generate -> JAXB Classes... 剩下的事情,大家都知道了

 //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.01.24 at 11:09:15 ���� CST
// package model; import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar; /**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
* &lt;complexContent>
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* &lt;sequence>
* &lt;element name="OrderNo" type="{http://www.w3.org/2001/XMLSchema}string"/>
* &lt;element name="OrderDateTime" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
* &lt;element name="CustomerName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* &lt;element name="OrderItems">
* &lt;complexType>
* &lt;complexContent>
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* &lt;sequence>
* &lt;element name="Produdct" maxOccurs="unbounded">
* &lt;complexType>
* &lt;complexContent>
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* &lt;sequence>
* &lt;element name="ProductNo" type="{http://www.w3.org/2001/XMLSchema}string"/>
* &lt;element name="ProductName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* &lt;element name="Price" type="{http://www.w3.org/2001/XMLSchema}float"/>
* &lt;element name="Amount" type="{http://www.w3.org/2001/XMLSchema}int"/>
* &lt;/sequence>
* &lt;/restriction>
* &lt;/complexContent>
* &lt;/complexType>
* &lt;/element>
* &lt;/sequence>
* &lt;/restriction>
* &lt;/complexContent>
* &lt;/complexType>
* &lt;/element>
* &lt;/sequence>
* &lt;/restriction>
* &lt;/complexContent>
* &lt;/complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"orderNo",
"orderDateTime",
"customerName",
"orderItems"
})
@XmlRootElement(name = "Order")
public class Order { @XmlElement(name = "OrderNo", required = true)
protected String orderNo;
@XmlElement(name = "OrderDateTime", required = true)
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar orderDateTime;
@XmlElement(name = "CustomerName", required = true)
protected String customerName;
@XmlElement(name = "OrderItems", required = true)
protected Order.OrderItems orderItems; /**
* Gets the value of the orderNo property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOrderNo() {
return orderNo;
} /**
* Sets the value of the orderNo property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOrderNo(String value) {
this.orderNo = value;
} /**
* Gets the value of the orderDateTime property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getOrderDateTime() {
return orderDateTime;
} /**
* Sets the value of the orderDateTime property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setOrderDateTime(XMLGregorianCalendar value) {
this.orderDateTime = value;
} /**
* Gets the value of the customerName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCustomerName() {
return customerName;
} /**
* Sets the value of the customerName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCustomerName(String value) {
this.customerName = value;
} /**
* Gets the value of the orderItems property.
*
* @return
* possible object is
* {@link Order.OrderItems }
*
*/
public Order.OrderItems getOrderItems() {
return orderItems;
} /**
* Sets the value of the orderItems property.
*
* @param value
* allowed object is
* {@link Order.OrderItems }
*
*/
public void setOrderItems(Order.OrderItems value) {
this.orderItems = value;
} /**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
* &lt;complexContent>
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* &lt;sequence>
* &lt;element name="Produdct" maxOccurs="unbounded">
* &lt;complexType>
* &lt;complexContent>
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* &lt;sequence>
* &lt;element name="ProductNo" type="{http://www.w3.org/2001/XMLSchema}string"/>
* &lt;element name="ProductName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* &lt;element name="Price" type="{http://www.w3.org/2001/XMLSchema}float"/>
* &lt;element name="Amount" type="{http://www.w3.org/2001/XMLSchema}int"/>
* &lt;/sequence>
* &lt;/restriction>
* &lt;/complexContent>
* &lt;/complexType>
* &lt;/element>
* &lt;/sequence>
* &lt;/restriction>
* &lt;/complexContent>
* &lt;/complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"produdct"
})
public static class OrderItems { @XmlElement(name = "Produdct", required = true)
protected List<Order.OrderItems.Produdct> produdct; /**
* Gets the value of the produdct property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the produdct property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getProdudct().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Order.OrderItems.Produdct }
*
*
*/
public List<Order.OrderItems.Produdct> getProdudct() {
if (produdct == null) {
produdct = new ArrayList<Order.OrderItems.Produdct>();
}
return this.produdct;
} /**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
* &lt;complexContent>
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* &lt;sequence>
* &lt;element name="ProductNo" type="{http://www.w3.org/2001/XMLSchema}string"/>
* &lt;element name="ProductName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* &lt;element name="Price" type="{http://www.w3.org/2001/XMLSchema}float"/>
* &lt;element name="Amount" type="{http://www.w3.org/2001/XMLSchema}int"/>
* &lt;/sequence>
* &lt;/restriction>
* &lt;/complexContent>
* &lt;/complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"productNo",
"productName",
"price",
"amount"
})
public static class Produdct { @XmlElement(name = "ProductNo", required = true)
protected String productNo;
@XmlElement(name = "ProductName", required = true)
protected String productName;
@XmlElement(name = "Price")
protected float price;
@XmlElement(name = "Amount")
protected int amount; /**
* Gets the value of the productNo property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProductNo() {
return productNo;
} /**
* Sets the value of the productNo property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProductNo(String value) {
this.productNo = value;
} /**
* Gets the value of the productName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProductName() {
return productName;
} /**
* Sets the value of the productName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProductName(String value) {
this.productName = value;
} /**
* Gets the value of the price property.
*
*/
public float getPrice() {
return price;
} /**
* Sets the value of the price property.
*
*/
public void setPrice(float value) {
this.price = value;
} /**
* Gets the value of the amount property.
*
*/
public int getAmount() {
return amount;
} /**
* Sets the value of the amount property.
*
*/
public void setAmount(int value) {
this.amount = value;
} } } }

order.java

上面是根据刚才的order.xsd生成的order类,package名称是model(当然生成java class的时候,你可以根据实际情况,设成任何自己需要的package名)

同时还会生成一个ObjectFactory类:

 //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.01.24 at 11:09:15 ���� CST
// package model; import javax.xml.bind.annotation.XmlRegistry; /**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the model package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory { /**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: model
*
*/
public ObjectFactory() {
} /**
* Create an instance of {@link Order.OrderItems }
*
*/
public Order.OrderItems createOrderOrderItems() {
return new Order.OrderItems();
} /**
* Create an instance of {@link Order }
*
*/
public Order createOrder() {
return new Order();
} /**
* Create an instance of {@link Order.OrderItems.Produdct }
*
*/
public Order.OrderItems.Produdct createOrderOrderItemsProdudct() {
return new Order.OrderItems.Produdct();
} }

ObjectFactory.java

4、Object <-> XML 的示例代码

     public void testXmlToObj() {
JAXBContext jc;
try {
jc = JAXBContext.newInstance("model");
Unmarshaller u = jc.createUnmarshaller();
String xmlFilePath = AppTest.class.getResource("/").getPath()
+ "order.xml";
System.out.println(xmlFilePath);
Order order = (Order) u.unmarshal(new File(xmlFilePath));
assertTrue(order.getOrderNo().equals("0000001"));
assertTrue(order.getCustomerName().equals("jimmy"));
for (int i = 0; i < order.getOrderItems().getProdudct().size(); i++) {
System.out.println(getProductDesc(order.getOrderItems()
.getProdudct().get(i)));
}
} catch (Exception e) {
e.printStackTrace();
}
} public void testObjToXml() {
try {
ObjectFactory of = new ObjectFactory();
Order order = of.createOrder();
Order.OrderItems orderItems = of.createOrderOrderItems(); Order.OrderItems.Produdct product1 = new Order.OrderItems.Produdct();
product1.setProductNo("A-01");
product1.setProductName("Car");
product1.setPrice(1000000);
product1.setAmount(1); orderItems.getProdudct().add(product1); Order.OrderItems.Produdct product2 = new Order.OrderItems.Produdct();
product2.setProductNo("B-01");
product2.setProductName("Book");
product2.setPrice(200);
product2.setAmount(2); orderItems.getProdudct().add(product2); order.setOrderItems(orderItems); JAXBContext jc = JAXBContext.newInstance("model");
Marshaller ms = jc.createMarshaller();
ms.setProperty("jaxb.encoding", "UTF-8");
ms.setProperty("jaxb.formatted.output", true);
String xmlFilePath = AppTest.class.getResource("/").getPath()
+ "order_new.xml";
ms.marshal(order, new File(xmlFilePath)); System.out.println("testObjToXml");
} catch (Exception e) {
e.printStackTrace(); }
}

object xml

示例源代码下载:jaxb-helloworld.zip (注:这是一个maven工程,命令行下直接mvn clean test,就可以测试)

java JAXB 学习的更多相关文章

  1. Java的学习之路

    记事本 EditPlus eclipse Java的学习软件,已经系统性学习Java有一段时间了,接下来我想讲一下我在Java学习用到的软件. 1.第一个软件:记事本 记事本是Java学习中最基础的编 ...

  2. Java多线程学习笔记

    进程:正在执行中的程序,其实是应用程序在内存中运行的那片空间.(只负责空间分配) 线程:进程中的一个执行单元,负责进程汇总的程序的运行,一个进程当中至少要有一个线程. 多线程:一个进程中时可以有多个线 ...

  3. Java Web 学习路线

    实际上,如果时间安排合理的话,大概需要六个月左右,有些基础好,自学能力强的朋友,甚至在四个月左右就开始找工作了.大三的时候,我萌生了放弃本专业的念头,断断续续学 Java Web 累计一年半左右,总算 ...

  4. Java基础学习-- 继承 的简单总结

    代码参考:Java基础学习小记--多态 为什么要引入继承? 还是做一个媒体库,里面可以放CD,可以放DVD.如果把CD和DVD做成两个没有联系的类的话,那么在管理这个媒体库的时候,要单独做一个添加CD ...

  5. 20145213《Java程序设计学习笔记》第六周学习总结

    20145213<Java程序设计学习笔记>第六周学习总结 说在前面的话 上篇博客中娄老师指出我因为数据结构基础薄弱,才导致对第九章内容浅尝遏止地认知.在这里我还要自我批评一下,其实我事后 ...

  6. [原创]java WEB学习笔记95:Hibernate 目录

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  7. Java多线程学习(转载)

    Java多线程学习(转载) 时间:2015-03-14 13:53:14      阅读:137413      评论:4      收藏:3      [点我收藏+] 转载 :http://blog ...

  8. java基础学习总结——java环境变量配置

    前言 学习java的第一步就要搭建java的学习环境,首先是要安装JDK,JDK安装好之后,还需要在电脑上配置"JAVA_HOME”."path”."classpath& ...

  9. Java Web学习系列——Maven Web项目中集成使用Spring、MyBatis实现对MySQL的数据访问

    本篇内容还是建立在上一篇Java Web学习系列——Maven Web项目中集成使用Spring基础之上,对之前的Maven Web项目进行升级改造,实现对MySQL的数据访问. 添加依赖Jar包 这 ...

随机推荐

  1. Android 自动生成的R类

    资源文件的使用分为在代码中使用和在其他资源文件中引用该资源文件.在我们编译一个Android应用时,Android会自动生成一个R类,在该类中根据不同的资源类型又生成了相应的内部类,该类包含了系统中使 ...

  2. C#程序猿电脑重装记录

    最近比较空了,闲的手痒,将自己的笔记本进行了重装,之前每次重装都没有记录,这次将本次重装过程记录下来,以便下次参考 1 首先不用说了WIN7旗舰版装好,驱动装好 2 开启Administrator用户 ...

  3. node.js学习之路

    (非原创) 目录 Nodejs的介绍 15个Nodejs应用场景 Nodejs学习路线图 1. Nodejs的介绍 Node.js的是建立在Chrome的JavaScript的运行时,可方便地构建快速 ...

  4. Java字符串中常见的10个问题

    下面是Java中10个最常见的关于字符串的问题. 怎样比较字符串?使用==还是equals() 简单的说,“==”用于判断引用是否相等,equals()用于判断值是否相等.除非你要比较两个字符串是否是 ...

  5. CMPP错误码说明

    与中国移动代码的对应关系. MI::zzzzSMSC返回状态报告的状态值为EXPIREDMJ:zzzzSMSC返回状态报告的状态值为DELETEDMK:zzzzSMSC返回状态报告的状态值为UNDEL ...

  6. JavaScript Patterns 4.8 Function Properties - A Memoization Pattern

    Gets a length property containing the number of arguments the function expects: function func(a, b, ...

  7. MySQL [Warning]: IP address 'xxxx' could not be resolved: Name or service not known

    MySQL的error log 出现大量的 DNS反解析错误. DNS解析是指,将 域名解析成ip地址: DNS反解析是指,将IP地址反解析成域名: Version: MySQL Community ...

  8. 【Unity】改变向量的方向而不改变其大小

    最近在做一个打砖块游戏时遇到一个小问题,就是小球有可能会在左右两个边界之间做循环往返运动而导致游戏无法继续进行下去,于是我打算让小球在垂直撞向边界时改变一下方向,但是速度不变,尝试了一些方法但是没有达 ...

  9. PostgreSql常用脚本

    添加表字段 ALTER TABLE public.university ADD COLUMN "Province" character varying(10); COMMENT O ...

  10. android 解决.XML提示ava.lang.NullPointerException at错误后XML没显示

    提示错误: java.lang.NullPointerException Exception details are logged in Window > Show View > Erro ...