JAXB: Unmarshalling does not always populate specific classes?

I have a problem with generating a JAXB class with which I was hoping to get some help. Here is the part of XML that is the source of my problem ...

<xs:complexType name="IDType"> <xs:choice minOccurs="0" maxOccurs="2"> <xs:element name="DriversLicense" minOccurs="0" maxOccurs="1" type="an..35" /> <xs:element name="SSN" minOccurs="0" maxOccurs="1" type="an..35" /> <xs:element name="CompanyID" minOccurs="0" maxOccurs="1" type="an..35" /> </xs:choice> </xs:complexType> <xs:simpleType name="an..35"> <xs:restriction base="an"> <xs:maxLength value="35" /> </xs:restriction> </xs:simpleType> <xs:simpleType name="an"> <xs:restriction base="xs:string"> <xs:pattern value="[ !-~]*" /> </xs:restriction> </xs:simpleType> 

... now this will generate a JAXBElement due to choice with maxOccurs > 1 . I want to avoid this, so I did this by changing the code to use the "Wrapper" element and moving maxOccurs to the sequence tag as follows:

 <xs:complexType name="IDType"> <xs:sequence maxOccurs="2"> <xs:element name=Wrapper> <xs:complexType> <xs:choice> <xs:element name="DriversLicense" minOccurs="0" maxOccurs="1" type="an..35" /> <xs:element name="SSN" minOccurs="0" maxOccurs="1" type="an..35" /> <xs:element name="CompanyID" minOccurs="0" maxOccurs="1" type="an..35" /> </xs:choice> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> <xs:simpleType name="an..35"> <xs:restriction base="an"> <xs:maxLength value="35" /> </xs:restriction> </xs:simpleType> <xs:simpleType name="an"> <xs:restriction base="xs:string"> <xs:pattern value="[ !-~]*" /> </xs:restriction> </xs:simpleType> 

To create a class, it seems to work just fine - the JAXB element is replaced with a list of wrappers as String (i.e. List<IDType.Wrapper<String> ) and compiled in order.

However, when I roll back the actual XML data into the generated classes, the data in the wrapper class does not populate, but JAXB does not throw an exception.

My question is: Do I need to change the circuit in another way to make this work? Or is there something I can add / modify / delete to generated code or annotations?

+4
source share
1 answer

This is a good idea, but pay attention to the following: according to your scheme, it is perfectly legal that your Wrapper element has no content. It contains a selection of optional items.

Secondly, you may not have a circuit check; then JAXB will not complain if your documents are violated. If you want to enable schema validation, get Unmarshaller and initialize as follows:

  unmarshaller.setValidating(true); SchemaFactory sf = SchemaFactory.newInstance( javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(new File("my-schema.xsd")); unmarshaller.setSchema(schema); 
+3
source

Source: https://habr.com/ru/post/1302001/


All Articles