JAXB生成具有属性组的架构

时间:2013-07-30 01:10:04

标签: xml jaxb

是否可以使用JAXB注释生成具有属性组的模式?如果是这样,怎么样?如果没有,为什么不呢?

1 个答案:

答案 0 :(得分:1)

TL; DR

JAXB (JSR-222)未定义将属性组输出到生成的架构中的方法。


从XML架构开始

下面是一个示例XML架构,其中包含两个引用相同属性组的复杂类型。

<?xml version="1.0" encoding="UTF-8"?>
<schema 
    xmlns="http://www.w3.org/2001/XMLSchema" 
    targetNamespace="http://www.example.org/schema" 
    xmlns:tns="http://www.example.org/schema" 
    elementFormDefault="qualified">

    <attributeGroup name="my-attribute-group">
        <attribute name="att1" type="string"/>
        <attribute name="att2" type="int"/>
    </attributeGroup>

    <complexType name="foo">
        <attributeGroup ref="tns:my-attribute-group"/>
        <attribute name="foo-att" type="string"/>
    </complexType>

    <complexType name="bar">
        <attributeGroup ref="tns:my-attribute-group"/>
        <attribute name="bar-att" type="string"/>
    </complexType>

</schema>

生成的模型

在下面生成的类中,我们看到属性组中的属性的处理方式与复杂类型中定义的属性相同。

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "foo")
public class Foo {

    @XmlAttribute(name = "foo-att")
    protected String fooAtt;
    @XmlAttribute(name = "att1")
    protected String att1;
    @XmlAttribute(name = "att2")
    protected Integer att2;

}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "bar")
public class Bar {

    @XmlAttribute(name = "bar-att")
    protected String barAtt;
    @XmlAttribute(name = "att1")
    protected String att1;
    @XmlAttribute(name = "att2")
    protected Integer att2;

}

从Java类开始

  

如果没有,为什么不呢?

现在我们知道属性组中的属性与常规属性的处理方式相同,因此需要额外的元数据来指示它们是同一属性组的一部分。需要注意确保随着FooBar类的发展,相同属性组的单独定义不会随着时间的推移而发散,从而导致错误。由于相同的XML文档可以由带有或不带属性组的XML模式表示,因此JAXB选择了更简单,更不容易出错的选项,即不提供生成它们的标准方法。

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "foo")
public class Foo {

    @XmlAttribute(name = "foo-att")
    protected String fooAtt;
    @XmlAttribute(name = "att1", fictionalPropertyAttributeGroup="my-attribute-group")
    protected String att1;
    @XmlAttribute(name = "att2", fictionalPropertyAttributeGroup="my-attribute-group")
    protected Integer att2;

}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "bar")
public class Bar {

    @XmlAttribute(name = "bar-att")
    protected String barAtt;
    @XmlAttribute(name = "att1", fictionalPropertyAttributeGroup="my-attribute-group")
    protected String att1;
    @XmlAttribute(name = "att2", fictionalPropertyAttributeGroup="my-attribute-group")
    protected Integer att2;

}