用来记录一些原创性的总结
在上一篇博文中介绍了通过schemagen指令来基于Java生成schema文件,本文将介绍使用JDK自带的xjc工具基于schema文件生成对应的Java文件。xjc的语法是:
xjc [options] schemaFile [-b bindinfo]
以下参数信息的说明摘自官方网站。
可选的options如下:
xjc schema1.xsd schema2.xsd schema3.xsd -b bindings123.xjb
或xjc schema1.xsd schema2.xsd schema3.xsd -b bindings1.xjb -b bindings2.xjb -b bindings3.xjb
。更详细的信息请参考官方文档。
以下是一份schema文档,我们可以通过xjc -p com.elim.jaxb schema.xsd
来指定生成的类都放在com.elim.jaxb
包中。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root" type="rootObject"/>
<xs:element name="sub1" type="subClass1"/>
<xs:element name="sub2" type="subClass2"/>
<xs:complexType name="rootObject">
<xs:sequence>
<xs:element name="prop1" type="xs:string" minOccurs="0"/>
<xs:element name="prop2" type="xs:string" minOccurs="0"/>
<xs:choice>
<xs:element ref="sub1"/>
<xs:element ref="sub2"/>
</xs:choice>
</xs:sequence>
</xs:complexType>
<xs:complexType name="superClass">
<xs:sequence>
<xs:element name="superProp1" type="xs:string" minOccurs="0"/>
<xs:element name="superProp2" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="subClass1">
<xs:complexContent>
<xs:extension base="superClass">
<xs:sequence>
<xs:element name="subProp1" type="xs:string" minOccurs="0"/>
<xs:element name="subProp2" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="subClass2">
<xs:complexContent>
<xs:extension base="superClass">
<xs:sequence>
<xs:element name="subProp1" type="xs:string" minOccurs="0"/>
<xs:element name="subProp2" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:schema>
生成的java类如下:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "rootObject", propOrder = {
"prop1",
"prop2",
"sub1",
"sub2"
})
public class RootObject {
protected String prop1;
protected String prop2;
protected SubClass1 sub1;
protected SubClass2 sub2;
//忽略get/set
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "superClass", propOrder = {
"superProp1",
"superProp2"
})
@XmlSeeAlso({
SubClass2 .class,
SubClass1 .class
})
public class SuperClass {
protected String superProp1;
protected String superProp2;
//省略get/set
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "subClass1", propOrder = {
"subProp1",
"subProp2"
})
public class SubClass1
extends SuperClass
{
protected String subProp1;
protected String subProp2;
//省略get/set
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "subClass2", propOrder = {
"subProp1",
"subProp2"
})
public class SubClass2
extends SuperClass
{
protected String subProp1;
protected String subProp2;
//省略get/set
}
以上就是本文的全部内容。