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. C#复习③

    C#复习③ 2016年6月16日 11:13 Main Declaration & Statement 声明和语句 1.一个程序包含的声明空间有哪些? Namespace : declarat ...

  2. html中相似的标签、属性的区别

    [1]<i></i> 和 <em></em>标签 相同:都是表示斜体. 区别: (1)<em>表示被强调呈现的内容,<i>是物理 ...

  3. pentaho cde popup弹出框口

    弹出窗口在pentaho cde里面相对比较容易,不过还是记录一下,以防时间久了,忘记关键参数. 先看一下效果图: 画出自己想要在弹出框展示的图形,把他的HtmlObject设置成弹出窗口,如图: 然 ...

  4. SQL中CHARINDEX()/INSTR()函数和SUBSTRING()/SUBSTR()函数

    一.SQLServer中的CHARINDEX() 和ORACLE中的INSTR()函数 1.INSTR(C1,C2[,I[,J]]) [功能]在一个字符串中搜索指定的字符,返回发现指定的字符的位置; ...

  5. ARM 汇编寻址方式

    ARM支持9种寻址方式:立即数寻址,寄存器寻址,寄存器偏移寻址,寄存器间接寻址,基址变址寻址,多寄存器寻址,相对寻址,堆栈寻址,块拷贝寻址. 立即数寻址 将数据直接存放的指令中发给CPU,首先由于AR ...

  6. Windows下常用软件工具的命令

    Linux上主要操作是命令,懂一点linux知识的都知道,其实windows下边很多工具也是可以用命令来操作打开的,这样会提高效率,节省很多的时间.下边就记录一下常用的命令. 一.常用命令 1.远程桌 ...

  7. Linux命令中使用正则表达式

    在使用grep.awk和sed命令时,需要使用正则表达式.比如我通过grep找代码编译结果中是否有错误.或者是否有我代码的错误.这里说下正则表达式基本的应用: • 匹配行首与行尾.• 匹配数据集.• ...

  8. Python使用QRCode模块生成二维码

    QRCode官网https://pypi.python.org/pypi/qrcode/5.1 简介python-qrcode是个用来生成二维码图片的第三方模块,依赖于 PIL 模块和 qrcode ...

  9. 用FineReport做的共建共享填报系统

    一.应用背景 随着信息技术的不断发展,快速开发出适合用户业务需求发展的填报报表是势在必然的,因此在不断的研究和分析下针对这一业务特点制作了此报表系统,以使不同开发商之间共建共享数据进行填报和统计分析的 ...

  10. COM中的线程模式

      Choosing the threading model for an object depends on the object's function. An object that does e ...