ITeye博客

Jaxb教程

ltian · 2011-10-02 20:10 · JAVA · 编程语言 · Markdown

转载自http://qmylove.spaces.live.com

Jaxb在J2EETurorial中有第16章有专门论述

Jaxb的Eclipse的插件https://jaxb-workshop.dev.java.net/plugins/eclipse/xjc-plugin.html

可以方便的从schema生成java类,而不是像下文第三步中那样用命令行。 开发步骤

  1. 下载例如 jaxb-2_1_8.zip从 https://jaxb.dev.java.net/2.1.8/ 解压,目录结构如下

clip_image002

  1. 定义xml文件的schema,用于定义xml文件的格式规范。本例为GolfCountryClub.xsd

一个最简单的schema

<schema xmlns="http://www.w3.org/2001/XMLSchema"

targetNamespace="http://www.example.org/GolfCountryClub"

xmlns:tns="http://www.example.org/GolfCountryClub">

<element name="GolfCourse" type="tns:GolfCourseType"

maxOccurs="unbounded" minOccurs="1">

<attribute name="NumberOfHoles" type="positiveInteger"

fixed="18">

  1. 运行xjc.bat或者xjc.sh脚本生成在schema中定义的java对象。

例如:解析GolfCountryClub.xsd并使用-p参数来指定包名

clip_image004

注:同样,可以使用schemagen.bat工具来根据生成的Java类生成schema,例如

clip_image006

生成的schema1.xsd内容如下,和我们原schema基本一致。

<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="GolfCountryClub">

xs:complexType

xs:sequence

<xs:element name="GolfCourse" type="GolfCourseType" maxOccurs="unbounded"/>

</xs:sequence>

</xs:complexType>

</xs:element>

<xs:complexType name="GolfCourseType">

xs:sequence

<xs:element name="Name" type="xs:string"/>

</xs:sequence>

<xs:attribute name="NumberOfHoles" type="xs:positiveInteger"/>

</xs:complexType>

</xs:schema>

  1. 使用javax.xml.bind.JAXB类的marshal静态方法来根据java对象生成xml文件。

新建一个空的Flex项目,将3中生成的类复制到java 源代码目录中。并将解压后lib文件夹下的jar文件复制到WEB-INFO/lib中。结构如图。

clip_image008

我们的目标是生成一个最简单的xml

<ns2:GolfCountryClub

xmlns:ns2="http://www.example.org/GolfCountryClub">

The best course

</ns2:GolfCountryClub>

下面我们新建一个类来生成上面的xml文档

package com.ibm.levin;

import java.io.StringWriter;

import java.io.Writer;

import java.math.BigInteger;

import java.util.ArrayList;

import javax.xml.bind.JAXBContext;

import javax.xml.bind.Marshaller;

import com.ibm.levin.*;

public class CreateXML {

public static void main(String args) {

ObjectFactory factory = new ObjectFactory();

GolfCountryClub gcc = factory.createGolfCountryClub();

GolfCourseType gctype = factory.createGolfCourseType();

gctype.setName("The best course");

gctype.setNumberOfHoles(BigInteger.valueOf(18));

gcc.golfCourse = new ArrayList();

gcc.golfCourse.add(0, gctype);

System.out.println(marshall(gcc));

}

public static String marshall(Object jaxbObject) {

try {

JAXBContext jc = JAXBContext.newInstance("com.ibm.levin");

Marshaller marshaller = jc.createMarshaller();

Writer outputWriter = new StringWriter();

marshaller.marshal(jaxbObject, outputWriter);

return outputWriter.toString();

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

}

运行后即可输出上述的xml文档。

  1. 实现javax.xml.bind.JAXB类的unmarshal静态方法从xml文件装载java对象。

略。

评论(1)

  1. #1 楼 · java0720 · 2012-12-05 13:32

评论功能维护中,当前仅展示历史评论。