java JAXB 学习
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>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="OrderNo" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="OrderDateTime" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
* <element name="CustomerName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="OrderItems">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Produdct" maxOccurs="unbounded">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ProductNo" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="ProductName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="Price" type="{http://www.w3.org/2001/XMLSchema}float"/>
* <element name="Amount" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </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>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Produdct" maxOccurs="unbounded">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ProductNo" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="ProductName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="Price" type="{http://www.w3.org/2001/XMLSchema}float"/>
* <element name="Amount" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </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>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ProductNo" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="ProductName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="Price" type="{http://www.w3.org/2001/XMLSchema}float"/>
* <element name="Amount" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </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 学习的更多相关文章
- Java的学习之路
记事本 EditPlus eclipse Java的学习软件,已经系统性学习Java有一段时间了,接下来我想讲一下我在Java学习用到的软件. 1.第一个软件:记事本 记事本是Java学习中最基础的编 ...
- Java多线程学习笔记
进程:正在执行中的程序,其实是应用程序在内存中运行的那片空间.(只负责空间分配) 线程:进程中的一个执行单元,负责进程汇总的程序的运行,一个进程当中至少要有一个线程. 多线程:一个进程中时可以有多个线 ...
- Java Web 学习路线
实际上,如果时间安排合理的话,大概需要六个月左右,有些基础好,自学能力强的朋友,甚至在四个月左右就开始找工作了.大三的时候,我萌生了放弃本专业的念头,断断续续学 Java Web 累计一年半左右,总算 ...
- Java基础学习-- 继承 的简单总结
代码参考:Java基础学习小记--多态 为什么要引入继承? 还是做一个媒体库,里面可以放CD,可以放DVD.如果把CD和DVD做成两个没有联系的类的话,那么在管理这个媒体库的时候,要单独做一个添加CD ...
- 20145213《Java程序设计学习笔记》第六周学习总结
20145213<Java程序设计学习笔记>第六周学习总结 说在前面的话 上篇博客中娄老师指出我因为数据结构基础薄弱,才导致对第九章内容浅尝遏止地认知.在这里我还要自我批评一下,其实我事后 ...
- [原创]java WEB学习笔记95:Hibernate 目录
本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...
- Java多线程学习(转载)
Java多线程学习(转载) 时间:2015-03-14 13:53:14 阅读:137413 评论:4 收藏:3 [点我收藏+] 转载 :http://blog ...
- java基础学习总结——java环境变量配置
前言 学习java的第一步就要搭建java的学习环境,首先是要安装JDK,JDK安装好之后,还需要在电脑上配置"JAVA_HOME”."path”."classpath& ...
- Java Web学习系列——Maven Web项目中集成使用Spring、MyBatis实现对MySQL的数据访问
本篇内容还是建立在上一篇Java Web学习系列——Maven Web项目中集成使用Spring基础之上,对之前的Maven Web项目进行升级改造,实现对MySQL的数据访问. 添加依赖Jar包 这 ...
随机推荐
- IrfanView 4.36 中文版发布了
IrfanView 4.36 简体中文便携版 小而快的图片浏览器 仅仅不到2M的小软件,功能却能与体积大到几十M的ACDSee相媲美!这个软件就是IrfanView.图片.音频.视频浏览,图片批量格式 ...
- Asp.net MVC验证哪些事(3)-- Remote验证及其改进(附源码)
表单中的输入项,有些是固定的,不变的验证规则,比如字符长度,必填等.但有些是动态的,比如注册用户名是否存在这样的检查,这个需要访问服务器后台才能解决.这篇文章将会介绍MVC中如何使用[RemoteAt ...
- Third glance in Go
在Go語言裏關於數組(Array),切片(Slice)和映射表(Map)的使用是非常常見的.有過其他語言編程背景的人會比較熟悉一下,但是也是因爲過於的熟悉,從而導致一個慣性思維,往往就會踢到“石頭”, ...
- mysql 去重,跨表更新,跨表删除
一.去重 1.查询出重复的记录 CREATE TABLE push_log_full_2013_10_30_tmp SELECT * FROM `push_log_full` WHERE time B ...
- PS网页设计教程——30个优秀的PS网页设计教程的中文翻译教程
PS网页设计教程--30个优秀的PS网页设计教程的中文翻译教程 作为编码者,美工基础是偏弱的.我们可以参考一些成熟的网页PS教程,提高自身的设计能力.套用一句话,"熟读唐诗三百首,不会作 ...
- JQuery 世界时间
根据表格的时间显示表格的时间,本机的时间,韩国的时间 <%@ Page Language="C#" AutoEventWireup ="true" Cod ...
- srping MVC 工程简单搭建
Spring版本:3.2.2.RELEASE 第一步:导入必须的jar包 spring-beans.jar spring-context.jar spring-core.jar spring-expr ...
- jenkins邮件通知功能
第部分:全局设置 第一步:进入jenkins的系统设置 第二步:设置管理员邮件地址: 第三步:下载email-ext插件并填写对应的内容: 第四部:填写邮件通知 第五步:以上就是系统管理里需要填写的全 ...
- 烂泥:rsync配置文件详解
本文由秀依林枫提供友情赞助,首发于烂泥行天下. 对于rsync服务器来说,最重要和复杂的就是它的配置了.rsync服务器的配置文件为/etc/rsyncd.conf,其控制认证.访问.日志记录等等. ...
- 010 使用netmap API接管网卡,接收数据包,回应ARP请求
一.本文目的: 上一节中,我们已经在CentOS 6.7 上安装好了netmap,也能接收和发送包了,这节我们来调用netmap中的API,接管网卡,对网卡上收到的数据包做分析,并回应ARP请求. 二 ...