Search code examples
javaxmljaxbjaxb2unmarshalling

JAXB multiple mappings for attribute


I'm just changing design errors made in the past, but want to keep backwards compatibility of my software. For this I would need some way to map two flavors of an xml file into one java bean. Can this be done using two JAXB annotations on one attribute/element? I understand the marshalling would be ambiguous, but the unmarshalling could work. Is there some nice way of doing this?

p.s.: I don't care about marshalling.


Solution

  • You can map twice:

    • the first time using annotations
    • the second time using XML resources.

    Or just two XML mappings instead of annotations.

    For XML resource mappings, there's a number of options:

    With Annox you can easily map twice using XML mapping resources with different extensions like MyClass.ann1.xml or MyClass.ann2.xml. (It's MyClass.ann.xml per default, but the adjustment is trivial.)

    Here's a sample of what mappings look like:

    <class xmlns="http://annox.dev.java.net" xmlns:annox="http://annox.dev.java.net" xmlns:jaxb="http://annox.dev.java.net/javax.xml.bind.annotation">
    
        <jaxb:XmlAccessorType value="FIELD"/>
        <jaxb:XmlType name="" propOrder="productName quantity usPrice comment shipDate"/>
        <field name="productName">
            <jaxb:XmlElement required="true"/>
        </field>
        <field name="usPrice">
            <jaxb:XmlElement name="USPrice" required="true"/>
        </field>
        <field name="shipDate">
            <jaxb:XmlSchemaType name="date"/>
        </field>
        <field name="partNum">
            <jaxb:XmlAttribute required="true"/>
        </field>
    </class>