Search code examples
javaxmlinheritancexsdschema-design

Inheritance in XML Schema definition (XSD) for Java objects


I need to create an XML schema definition (XSD) that describes Java objects.

I was wondering how to do this when the objects in question inherit from a common base class with a type parameter.

public abstract class Rule<T> { ... }

public abstract class TimeRule extends Rule<XTime> { ... }

public abstract class LocationRule extends Rule<Location> { ... }

public abstract class IntRule extends Rule<Integer> { ... }

....

(where XTime and Location are custom classes defined elsewhere)

How would I go about constructing an XSD that such that I can have XML nodes that represent each of the subclasses of Rule<T> - without the XSD for each of them repeating their common contents?

Thank you!


Solution

  • Conisder JAXB for XML Schema -> Java compilation.

    XML Schema gives some possibilities for modelling iheritance:

    <xs:complexType name="baseType">
        <xs:sequence>
            <xs:element name="a" type="xs:string"/>
            <xs:element name="b" type="xs:long"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="extendedType">
        <xs:complexContent>
            <xs:extension base="baseType">
                <xs:sequence>
                    <xs:element name="c" type="xs:dateTime"/>
                    <xs:element name="d" type="xs:base64Binary"/>
                </xs:sequence>
            </xs:extension>
        </xs:complexContent>
    </xs:complexType>
    

    However, I don't think you can achieve exactly the Java code you're posting. You can, nevertheless get somewhat close with the inheritance plugin.