JAXB 示例

原文: https://docs.oracle.com/javase/tutorial/jaxb/intro/examples.html

以下部分描述如何使用 JAXB RI 包中包含的示例应用程序。 JAXB RI 包可从 http://jaxb.java.net 获得。下载并安装 JAXB RI 软件包。这些示例位于 jaxb-ri-install / samples /目录中。这些示例演示并构建了关键的 JAXB 特性和概念。按照提供的顺序执行这些步骤。

阅读本节后,您应该对 JAXB 感到满意,您可以:

  • 从 XML 模式生成 JAXB Java 类
  • 使用模式派生的 JAXB 类在 Java 应用程序中解组和编组 XML 内容
  • 使用模式派生的 JAXB 类创建 Java 内容树
  • 在解组和运行时验证 XML 内容
  • 自定义 JAXB 模式到 Java 绑定

本文档描述了三组示例:

  • 基本示例(Modify Marshal,Unmarshal Validate)演示了基本的 JAXB 概念,例如使用默认设置和绑定解组,编组和验证 XML 内容。
  • 自定义示例(自定义内联,数据类型转换器,外部自定义)演示了自定义 XML 模式到 Java 对象的默认绑定的各种方法。
  • java-to-schema 示例显示如何使用注释将 Java 类映射到 XML 模式。

Note: The basic and customize examples are based on a Purchase Order scenario. Each uses an XML document, po.xml, written against an XML schema, po.xsd. These documents are derived from the W3C XML Schema Part 0: Primer, edited by David C. Fallside.


basic 和 customize 示例目录包含几个基本文件:

  • po.xsd是 XML 模式,用作 JAXB 绑定编译器的输入,并从中生成模式派生的 JAXB Java 类。对于 Customize Inline 和 Datatype Converter 示例,此文件包含内联绑定自定义。
  • po.xml是包含示例 XML 内容的 Purchase Order XML 文件,它是在每个示例中解组到 Java 内容树中的文件。这个文件在每个例子中几乎相同;有一些小的内容差异,以突出不同的 JAXB 概念。
  • Main.java是每个示例的主要 Java 类。
  • build.xml是为方便起见而提供的 Ant 项目文件。使用 Ant 工具自动生成,编译和运行模式派生的 JAXB 类。 build.xml文件因示例而异。
  • `内联自定义示例中的 MyDatatypeConverter.java`是用于提供自定义数据类型转换的 Java 类。
  • 外部自定义示例中的binding.xjb是一个外部绑定声明文件,它传递给 JAXB 绑定编译器以自定义默认的 JAXB 绑定。

下表简要描述了基本,自定义和 Java 到架构的 JAXB 示例。

表:基本 JAXB 示例

示例名称 描述
修改元帅 演示如何修改 Java 内容树。
Unmarshal Validate 演示如何在解组期间启用验证。

表:自定义 JAXB 示例

示例名称 描述
自定义内联 演示如何通过在 XML 模式中使用内联注释来自定义默认 JAXB 绑定。
数据类型转换器 说明 XML simpleType定义与 Java 数据类型的交替,更简洁的绑定,类似于 Customize Inline 示例。
外部自定义 说明如何使用外部绑定声明文件将只读模式的绑定自定义传递给 JAXB 绑定编译器。

表:Java-to-Schema JAXB 示例

示例名称 描述
创造元帅 演示如何使用 ObjectFactory 类创建 Java 内容树并将其编组为 XML 数据。它还演示了如何将内容添加到 JAXB List 属性。
XmlAccessorOrder 说明如何使用 Java 类中的@XmlAccessorOrder@ XmlType.propOrder映射注释来控制 Java 类型编组或解组 XML 内容的顺序。
XmlAdapter 说明如何使用接口XmlAdapter和注释@XmlJavaTypeAdapter来提供 XML 内容到HashMap (字段)的自定义映射,使用整数( int )作为键和一个字符串( String )作为值。
XmlAttribute 说明如何使用注释@XmlAttribute来定义要作为 XML 属性处理的属性或字段。
XmlRootElement 说明如何使用注释@XmlRootElement为相应类的 XML 模式类型定义 XML 元素名称。
XmlSchemaType 类 说明如何使用注释@XmlSchemaType来自定义属性或字段到 XML 内置类型的映射。
XmlType 说明如何使用注释@XmlType将类或枚举类型映射到 XML 模式类型。

JAXB 编译器选项

JAXB XJC 模式绑定编译器将源 XML 模式转换或绑定到 Java 编程语言中的一组 JAXB 内容类。编译器类xjc在 Solaris / Linux 上提供为: xjc.sh ,在 Windows 上的 JAXB RI 包中提供xjc.batxjc类包含在 JDK 类库中(在 tools.jar 中)。

xjc.shxjc.bat都采用相同的命令行选项。您可以通过调用脚本而无需任何选项或使用-help开关来显示快速使用说明。语法如下:

  1. xjc [-options ...] <schema file/URL/dir/jar>... [-b >bindinfo<] ...

如果指定了dir ,则将编译目录中的所有模式文件。如果指定了jar ,将编译/META-INF/sun-jaxb.episode 绑定文件。

xjc命令行选项如下:

-nv

Do not perform strict validation of the input schema or schemas. By default, xjc performs strict validation of the source schema before processing. Note that this does not mean the binding compiler will not perform any validation; it will just perform a less-strict validation.

-extension

By default, the XJC binding compiler strictly enforces the rules outlined in the Compatibility chapter of the JAXB Specification. In the default (strict) mode, you are also limited to using only the binding customizations defined in the specification. By using the -extension switch, you are allowed to use the JAXB Vendor Extensions.

-b file

Specify one or more external binding files to process. (Each binding file must have its own -b switch.) The syntax of the external binding files is flexible. You may have a single binding file that contains customizations for multiple schemas or you can break the customizations into multiple bindings files. In addition, the ordering of the schema files and binding files on the command-line does not matter.

-d dir

By default, the XJC binding compiler generates Java content classes in the current directory. Use this option to specify an alternate output directory. The directory must already exist; the XJC binding compiler does not create one for you.

-p package

Specify an alternate output directory. By default, the XJC binding compiler will generate the Java content classes in the current directory. The output directory must already exist; the XJC binding compiler does not create one for you.

-httpproxy proxy

Specify the HTTP/HTTPS proxy. The format is [``_user_``[:``_password_``]@]``_proxyHost_``[:``_proxyPort_``]. The old -host and -port options are still supported by the Reference Implementation for backward compatibility, but they have been deprecated.

-httpproxyfile f

Works like the -httpproxy option but takes the argument in a file to protect password.

-classpath arg

Specify where to find client application class files used by the <jxb:javaType> and <xjc:superClass> customizations.

-catalog file

Specify catalog files to resolve external entity references. Supports TR9401, XCatalog, and OASIS XML Catalog format. For more information, see the XML Entity and URI Resolvers document or examine the catalog-resolver sample application.

-readOnly

Force the XJC binding compiler to mark the generated Java sources as read-only. By default, the XJC binding compiler does not write-protect the Java source files it generates.

-npa

Suppress the generation of package level annotations into **/package-info.java. Using this switch causes the generated code to internalize those annotations into the other generated classes.

-no-header

Suppress generation of a file header with timestamp.

-target (2.0|2.1)

Behave like XJC 2.0 or 2.1 and generate code that doesnt use any XJC 2.2 features.

-enableIntrospection

Enable correct generation of Boolean getters/setters to enable Bean Introspection apis.

-contentForWildcard

Generates content property for types with multiple xs:any derived elements.

-xmlschema

Treat input schemas as W3C XML Schema (default). If you do not specify this switch, your input schemas are treated as W3C XML Schema.

-verbose

Be extra verbose in compiler output.

-quiet

Suppress compiler output, such as progress information and warnings.

-help

Display a brief summary of the compiler switches.

-version

Display the compiler version information.

-fullversion

Display the compiler full version information.

-Xinject-code

Inject specified Java code fragments into the generated code.

-Xlocator

Enable source location support for generated code.

-Xsync-methods

Generate accessor methods with the synchronized keyword.

-mark-generated

Mark the generated code with the -@javax.annotation. Generated annotation.

-episode _FILE_

Generate the episode file for separate compilation.

JAXB 架构生成器选项

JAXB 模式生成器schemagen为 Java 类中引用的每个命名空间创建模式文件。可以使用适用于您的平台的bin目录中的相应schemagen shell 脚本来启动模式生成器。模式生成器仅处理 Java 源文件。如果 Java 源代码引用其他类,则必须可以从系统 CLASSPATH 环境变量访问这些源代码。否则生成架构时将发生错误。无法控制生成的模式文件的名称。

您可以通过调用脚本而无需任何选项或使用-help选项来显示快速使用说明。语法如下:

  1. schemagen [-d path]
  2. [java-source-files]

-d _ 路径*选项指定处理器生成的和javac生成的类文件的位置。

关于 Schema-to-Java 绑定

当您针对基本示例(Unmarshal Read,Modify Marshal,Unmarshal Validate)中使用的po.xsd XML 模式运行 JAXB 绑定编译器时,JAXB 绑定编译器生成名为primer 的 Java 包。 po包含类,如下表所述。

表:基本示例中的模式派生 JAXB 类

描述
primer / po / Items.java 绑定到模式complexType的公共接口,命名为Items
primer / po / ObjectFactory.java 公共类扩展com.sun.xml.bind.DefaultJAXBContextImpl ;用于创建指定接口的实例。例如, ObjectFactory createComment()方法实例化Comment对象。
primer / po / PurchaseOrderType.java 公共接口绑定到名为PurchaseOrderType的模式complexType
primer / po / USAddress.java 绑定到模式complexType的公共接口,名为USAddress

下表描述了这些类及其对基本示例的源 XML 模式的特定绑定。

表:基本示例的 Schema-to-Java 绑定

XML Schema:

  1. &lt;xsd:schema xmlns:xsd=
  2. "http://www.w3.org/2001/XMLSchema"&gt;

JAXB 绑定:


XML Schema:

  1. &lt;xsd:complexType
  2. name="PurchaseOrderType"&gt;
  3. &lt;xsd:sequence&gt;
  4. &lt;xsd:element
  5. name="shipTo"
  6. type="USAddress"/&gt;
  7. &lt;xsd:element
  8. name="billTo"
  9. type="USAddress"/&gt;
  10. &lt;xsd:element
  11. ref="comment"
  12. minOccurs="0"/&gt;
  13. &lt;xsd:element
  14. name="items"
  15. type="Items"/&gt;
  16. &lt;/xsd:sequence&gt;
  17. &lt;xsd:attribute
  18. name="orderDate"
  19. type="xsd:date"/&gt;
  20. &lt;/xsd:complexType&gt;

JAXB 绑定:PurchaseOrderType.java


XML Schema:

  1. &lt;xsd:complexType
  2. name="USAddress"&gt;
  3. &lt;xsd:sequence&gt;
  4. &lt;xsd:element
  5. name="name"
  6. type="xsd:string"/&gt;
  7. &lt;xsd:element
  8. name="street"
  9. type="xsd:string"/&gt;
  10. &lt;xsd:element
  11. name="city"
  12. type="xsd:string"/&gt;
  13. &lt;xsd:element
  14. name="state"
  15. type="xsd:string"/&gt;
  16. &lt;xsd:element
  17. name="zip"
  18. type="xsd:decimal"/&gt;
  19. &lt;/xsd:sequence&gt;
  20. &lt;xsd:attribute
  21. name="country"
  22. type="xsd:NMTOKEN"
  23. fixed="US"/&gt;
  24. &lt;/xsd:complexType&gt;

JAXB 绑定:USAddress.java


XML Schema:

  1. &lt;xsd:complexType
  2. name="Items"&gt;
  3. &lt;xsd:sequence&gt;
  4. &lt;xsd:element
  5. name="item"
  6. minOccurs="1"
  7. maxOccurs="unbounded"&gt;

JAXB 绑定:Items.java


XML Schema:

  1. &lt;xsd:complexType&gt;
  2. &lt;xsd:sequence&gt;
  3. &lt;xsd:element
  4. name="productName"
  5. type="xsd:string"/&gt;
  6. &lt;xsd:element
  7. name="quantity"&gt;
  8. &lt;xsd:simpleType&gt;
  9. &lt;xsd:restriction
  10. base="xsd:positiveInteger"&gt;
  11. &lt;xsd:maxExclusive
  12. value="100"/&gt;
  13. &lt;/xsd:restriction&gt;
  14. &lt;/xsd:simpleType&gt;
  15. &lt;/xsd:element&gt;
  16. &lt;xsd:element
  17. name="USPrice"
  18. type="xsd:decimal"/&gt;
  19. &lt;xsd:element
  20. ref="comment"
  21. minOccurs="0"/&gt;
  22. &lt;xsd:element
  23. name="shipDate"
  24. type="xsd:date"
  25. minOccurs="0"/&gt;
  26. &lt;/xsd:sequence&gt;
  27. &lt;xsd:attribute
  28. name="partNum"
  29. type="SKU"
  30. use="required"/&gt;
  31. &lt;/xsd:complexType&gt;

JAXB 绑定:Items.ItemType


XML Schema:

  1. &lt;/xsd:element&gt;
  2. &lt;/xsd:sequence&gt;
  3. &lt;/xsd:complexType&gt;

JAXB 绑定:


XML Schema:

  1. &lt;!-- Stock Keeping Unit, a code for
  2. identifying products --&gt;

JAXB 绑定:


XML Schema:

  1. &lt;xsd:simpleType
  2. name="SKU"&gt;
  3. &lt;xsd:restriction
  4. base="xsd:string"&gt;
  5. &lt;xsd:pattern
  6. value="\d{3}-[A-Z]{2}"/&gt;
  7. &lt;/xsd:restriction&gt;
  8. &lt;/xsd:simpleType&gt;

JAXB 绑定:


XML Schema:

  1. &lt;/xsd:schema&gt;

JAXB 绑定:

模式派生的 JAXB 类

接下来的部分将简要说明 JAXB 绑定编译器为示例生成的以下各个类的功能:

项目

Items.java中:

  • 项目类是primer.po包的一部分。
  • 该类为ItemsItemType提供公共接口。
  • 此类的实例化中的内容绑定到 XML ComplexTypes Items及其子元素ItemType
  • Item提供getItem()方法。
  • ItemType提供以下方法:
    • getPartNum();
    • setPartNum(String value);
    • getComment();
    • setComment(java.lang.String value);
    • getUSPrice();
    • setUSPrice(java.math.BigDecimal value);
    • getProductName();
    • setProductName(String value);
    • getShipDate();
    • setShipDate(java.util.Calendar value);
    • getQuantity();
    • setQuantity(java.math.BigInteger value);

ObjectFactory

ObjectFactory.java中:

  • ObjectFactory类是primer.po包的一部分。
  • ObjectFactory提供工厂方法,用于实例化 Java 内容树中表示 XML 内容的 Java 接口。
  • 方法名称通过连接生成:
    • 字符串常量创建
    • 所有外部 Java 类名称,如果 Java 内容接口嵌套在另一个接口中。
    • Java 内容接口的名称。

例如,在这种情况下,对于 Java 接口primer.po.Items.ItemTypeObjectFactory创建方法createItemsItemType()

PurchaseOrderType Class

PurchaseOrderType.java中:

  • PurchaseOrderType类是primer.po包的一部分。
  • 此类的实例化中的内容绑定到名为PurchaseOrderType的 XML 模式子元素。
  • PurchaseOrderType是一个提供以下方法的公共接口:
    • getItems();
    • setItems(primer.po.Items value);
    • getOrderDate();
    • setOrderDate(java.util.Calendar value);
    • getComment();
    • setComment(java.lang.String value);
    • getBillTo();
    • setBillTo(primer.po.USAddress value);
    • getShipTo();
    • setShipTo(primer.po.USAddress value);

USAddress Class

USAddress.java中:

  • USAddress类是primer.po包的一部分。
  • 此类的实例化中的内容绑定到名为USAddress的 XML 架构元素。
  • USAddress是一个提供以下方法的公共接口:
    • getState();
    • setState(String value);
    • getZip();
    • setZip(java.math.BigDecimal value);
    • getCountry();
    • setCountry(String value);
    • getCity();
    • setCity(String value);
    • getStreet();
    • setStreet(String value);
    • getName();
    • setName(String value);