JAXB用原始类型替换复杂类型

时间:2010-07-12 13:43:21

标签: java jaxb

在我的模式中,我有一些类型只是扩展一个简单的XSD类型(int或string)。 JAXB为每种类型创建一个单独的java类。我想删除此中间类并将JAXB配置为尽可能使用原语(例如,将CountryType替换为java.lang.String,将DocumentType替换为intlava.lang.Integer。例如,对于给定的XSD,最好有DestinationType.setDocumentType(int)List<String> StatesType.getCountry()。我很乐意为此编写类型范围an adapter,但看起来只支持来自原始XML类型的转换。也许有可能进行每个属性的类型转换?请提供任何可以提供帮助的JAXB绑定自定义示例。

<?xml version="1.0" encoding="UTF-8"?>
<schema
    xmlns="http://www.w3.org/2001/XMLSchema"
    xmlns:exch="http://www.mycompany.org/exchange"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    targetNamespace="http://www.mycompany.org/exchange"
    elementFormDefault="qualified" attributeFormDefault="unqualified">

    <complexType name="countryType">
        <simpleContent>
            <extension base="string"/>
        </simpleContent>
    </complexType>

    <complexType name="statesType">
        <sequence maxOccurs="unbounded">
            <element name="country" type="exch:countryType"/>
        </sequence>
    </complexType>

    <complexType name="documentType">
        <simpleContent>
            <extension base="integer"/>
        </simpleContent>
    </complexType>

    <complexType name="destinationType">
        <sequence>
            <element name="states" type="exch:statesType" maxOccurs="1"/>
            <element name="document-type" type="exch:documentType" minOccurs="1" maxOccurs="1"/>
        </sequence>
    </complexType>
</schema>

2 个答案:

答案 0 :(得分:2)

另一种可能性,您可以更改架构吗?:

以下架构更改将生成所需的对象模型。

使用:

<simpleType name="documentType">
    <restriction base="integer"/>
</simpleType>

而不是:

<complexType name="documentType"> 
    <simpleContent> 
        <extension base="integer"/> 
    </simpleContent> 
</complexType> 

答案 1 :(得分:0)

好问题。在过去,我通过XSLT预处理步骤运行模式解决了这个问题,“扁平化”了类型层次结构,同时保留了文档的语义。

例如,XSLT将删除documentType类型的定义,并将documentType的每个引用替换为integer。生成的已处理模式仍然代表相同的实例文档,但更简单,并且可以实现更好的绑定。

这个(相当不完整的)解决方案可以应用于与过度复杂的模式有关的许多类似问题(例如,用选择结构替换替换组)。

相关问题