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. .NET项目工程生成一份项目帮助文档chm--Sandcastle工具

    Sandcastle的,由Microsoft创建的,是从创建MSDN风格的文档中使用的工具.NET程序集和关联的XML注释文件.目前的版本是 2010年6月发布.这是命令行并没有GUI前端,项目管理功 ...

  2. AngularJS 简介

    AngularJS 是一个 JavaScript 框架. 它可通过 <script> 标签添加到 HTML 页面. <script src="http://apps.bdi ...

  3. my_strcmp()

    void my_strcmp(const char* s1,const char* s2){ int i=0; while(*(s1+i)!='\0'||*(s2+i)!='\0'){ if(*(s1 ...

  4. POSIX, Bash, GPL etc

    POSIX , SUS, XSI Portable Operating System Interface POSIX是给Unix/Linux系统使用的通用调用接口(SCI, System Call I ...

  5. Toritoisegit记住用户名密码

    TortoiseGit每次连接git都得输入密码了,如果我们用到的比较频繁这样是很麻烦的,那么下面我们来看一篇关于window设置TortoiseGit连接git不用每次输入用户名和密码的配置,具体的 ...

  6. 1---------java调用NLPIR(ICTCLAS2016)实现分词功能

    备注:win7 64位系统,netbeans编程 NLPIR分词系统,前身是2000年发布的ICTCLAS,2009年更为现名.张华平博士打造. 实现步骤: 1.在Netbeans中,文件→新建项目→ ...

  7. 启动mysql错误ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’ (2)

    ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’ ( ...

  8. java 知识点随记

    JAVA 读取配置文件: Properties props= new Properties();//文件在src目录下,编译会被加载到classpath下. Props.load(Test.class ...

  9. APDU

    # APDU # 定义:APDU(ApplicationProtocolDataUnit--应用协议数据单元).协议数据单元PDU(ProtocolDataUnit)是指对等层次之间传递的数据单位.协 ...

  10. Eclipse较为常用快捷键

    今天在学习Eclipse的使用时,Mark了一些较为常用的快捷键,拿出来和大家分享一下: Ctrl+1 快捷修复 Ctrl+D 快捷删除行 Shift+Enter 在当前行任意位置光标跳转到下一行 C ...