Marshalling problem in JAXB (XSD inheritance)

Problem:

javax.xml.bind.MarshalException - with linked exception:com.sun.istack.SAXException2: Instance of "com.gk.VegPizzaType" is substituting "com.gk.PizzaType", but "com.gk.VegPizzaType" is bound to an anonymous type

Given Problematic XSD:

<xs:complexType name="PizzaType" /> <xs:element name="Pizza"> <xs:complexType> <xs:sequence> <xs:element name="PizzaType" type="rem:PizzaType" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="VegPizzaType"> <xs:complexType name="VegPizzaType"> <xs:complexContent> <xs:extension base="rem:PizzaType"> <xs:attribute name="type" use="required"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="Corn" /> <xs:enumeration value="Tomato"/> <xs:enumerationvalue="Capsicum" /> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="NonVegPizzaType"> <xs:complexType> <xs:complexContent> <xs:extension base="rem:PizzaType"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="Chicken" /> <xs:enumeration value="Fish" /> </xs:restriction> </xs:simpleType> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element>

When we do marshalling

Marshaller marshaller = JAXBContext.newInstance(Pizza.class).createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); marshaller.setSchema(schema); marshaller.marshal(pizzaInstance, writer); We get above stated exception i.e. javax.xml.bind.MarshalException

Solution:

Need to change definition for ‘NonVegPizzaType’ and ' VegPizzaType'

<xs:complexType name="VegPizzaType"> <xs:complexContent> <xs:extension base="rem:PizzaType"> <xs:attribute name="type" use="required"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="Corn" /> <xs:enumeration value="Tomato" /> <xs:enumeration value="Capsicum" /> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="NonVegPizzaType"> <xs:complexContent> <xs:extension base="rem:PizzaType"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="Chicken" /> <xs:enumeration value="Fish" /> </xs:restriction> </xs:simpleType> </xs:extension> </xs:complexContent> </xs:complexType>

In previous XSD, 'NonVegPizzaType' and ' VegPizzaType' were elements, now in, solution you can observe them as complexType .

Conclusion

if we want to use inheritance in xsd frame work , you should not use extension tag in element tag rather child and parent both should be complexType tags only.

And in xml i.e. instance of xsd, if you want to create object of type VegPizzaType

		
<PizzaType type="Corn" xmlns:xsi="http://www.w3.org/2001/ XMLSchema-instance" xsi:type="VegPizzaType" /> xsi:type="VegPizzaType" specifies that this object is of type veg pizza
HTML Comment Box is loading comments...