Julius Bullinger
Julius Bullinger

Reputation: 1186

Reduce code duplication in JAXB-generated classes from two very similar (but different) schemas

I have a (very large) XML schema with the namespace myschema_1.0. Recently, this schema was updated with some minimal but significant changes, resulting in a new version with the namespace myschema_1.1.

My application needs to support both versions, so I've generated Java classes for each. JAXB places them in separate packages, but since most definitions are identical, this results in a lot of code duplication in both the generated files and the application logic.

Constraints and attempts

Simple Example

Consider the following simplified example:

Schema Version 1.0 (myschema_1.0.xsd):

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="myschema_1.0">
    <xs:element name="Person">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="FirstName" type="xs:string"/>
                <xs:element name="LastName" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

Schema Version 1.1 (myschema_1.1.xsd):

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="myschema_1.1">
    <xs:element name="Person">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="FirstName" type="xs:string"/>
                <xs:element name="LastName" type="xs:string"/>
                <xs:element name="MiddleName" type="xs:string" minOccurs="0"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

For these schemas, JAXB generates the following classes in separate packages:

Although the Person class in myschema_1.0 and myschema_1.1 are almost identical, except for the optional MiddleName field, any code that works with the Person object needs to handle both versions separately.

The Question

Is there a way to automatically extract common definitions or create shared interfaces without manually writing thousands of adapters or interfaces? I've thought about using tools like Schematron or XMLSpy to identify common elements, but I’m unsure how to integrate them into my JAXB workflow.

Given that I cannot change the schema files, how can I effectively reduce this duplication?

Upvotes: 0

Views: 48

Answers (0)

Related Questions