I have a small problem with JAXB, but unfortunately I was not able to find answer.
I have a class Customer, with 2 fields name and city, the mapping is done using annotations and both fields are marked as required and not nillable.
@XmlRootElement(name = "customer")
public class Customer {
enum City {
PARIS, LONDON, WARSAW
}
@XmlElement(name = "name", required = true, nillable = false)
public String name;
@XmlElement(name = "city", required = true, nillable = false)
public City city;
@Override
public String toString(){
return String.format("Name %s, city %s", name, city);
}
}
However, when I submit such XML file:
<customer>
<city>UNKNOWN</city>
</customer>
I will receive a Customer instance with both fields set to null.
Shouldn't there be a validation exception or am I missing something in the mapping?
To unmarshal I use:
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) unmarshaller.unmarshal(in);
JAXB definitionsMarshalling is the process of transforming Java objects into XML documents. Unmarshalling is the process of reading XML documents into Java objects.
Ignore XML Attribute. You can specify ignore="true" or ignore="false". The default value is false. Specifying ignore="false" has no effect on the attribute value assigned when an object of the type specified in the rule is created and no effect on the constraints.
The JAXB annotations defined in the javax. xml. bind. annotations package can be used to customize Java program elements to XML schema mapping.
You need to use the schema to validate. JAXB can't do validation on its own.
SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(ClassUtils.getDefaultClassLoader().getResource(schemaPath));
unmarshaller.setSchema(schema);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With