自定义JAXB绑定

时间:2017-07-10 06:17:07

标签: java xsd jaxb

我是JAXB世界的新手,面临着一个问题。首先,我甚至不知道是否可能,如果有可能,那么该如何做。

我有这个XSD文件(修剪版本)

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:complexType name="nillableString">
    <xsd:simpleContent>
      <xsd:extension base="xsd:string">
        <xsd:attribute name="nil" type="xsd:boolean"/>
      </xsd:extension>
    </xsd:simpleContent>
  </xsd:complexType>

  <xsd:simpleType name="NillableIntegerType">
    <xsd:restriction base="xsd:token">
      <!-- not the right pattern, but the right pattern isn't working ("[-+]?\d*") -->
      <xsd:pattern value="[\-+0-9]*"/>
    </xsd:restriction>
  </xsd:simpleType>
    <xsd:complexType name="nillableInteger">
    <xsd:simpleContent>
      <xsd:extension base="NillableIntegerType">
        <xsd:attribute name="nil" type="xsd:boolean"/>
      </xsd:extension>
    </xsd:simpleContent>
  </xsd:complexType>

  <xsd:element name="mainclass">
    <xsd:complexType>
      <xsd:choice minOccurs="0" maxOccurs="unbounded">
        <xsd:element ref="prop1" minOccurs="0"/>
        <xsd:element ref="prop2" minOccurs="0"/>
      </xsd:choice>
      <xsd:attribute name="product" use="optional" type="xsd:string"/>
    </xsd:complexType>
  </xsd:element>

  <xsd:element name="prop1">
    <xsd:complexType>
      <xsd:choice minOccurs="0" maxOccurs="unbounded">
        <xsd:element name="name" type="nillableString" minOccurs="0"/>
      </xsd:choice>
    </xsd:complexType>
  </xsd:element>

  <xsd:element name="prop2">
    <xsd:complexType>
      <xsd:choice minOccurs="0" maxOccurs="unbounded">
        <xsd:element name="priority" type="nillableInteger" minOccurs="0"/>
        <xsd:element name="backup_rule" type="nillableString" minOccurs="0"/>
      </xsd:choice>
      <!-- no attributes -->
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

然后我使用xjc工具从这个XSD文件生成Java Bean。但是,我的Java bean属性看起来像这样

@XmlElements({
    @XmlElement(name = "prop1", type = Prop1.class),
    @XmlElement(name = "prop2", type = Prop2.class)
})
protected List<Object> prop1OrProp2; 

但是,我希望我的bean显示为

@XmlElement(name = "prop1", type = Prop1.class)
protected Prop1 prop1;

@XmlElement(name = "prop2", type = Prop2.class)
protected Prop2 prop2;

这甚至可能吗?如果是,请指出我该怎么办? (我尝试跟随http://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.5/tutorial/doc/JAXBUsing4.html#wp148366,但我完全迷失了)

通过这种方式,我可以明确地设置每个属性。这只是一个简单的例子,但在实际的XSD中,我有大约30个属性。

0 个答案:

没有答案