Unmarshaller with No Default Data Validation

Q

Why the Unmarshaller is not generating error on invalid data given in the XML file?

✍: FYIcenter.com

A

In the JRE 8 implementation of JAXB, the Unmarshaller does not have any default data validation. If the input XML has any invalid data, the Unmarshaller will will throw data parsing exceptions or assign null values.

1. Null value example - Create the following invalid XML file, UserError1.xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<User ID="2">
    <BirthDate>Unknown</BirthDate>
    <Name>Frank Y. Ivy</Name>
    <Sex>Male</Sex>
</User>

Run the MyXmlToUser.java program given in the previous tutorial. The Unmarshaller returns null for the invalid date in the XML:

\fyicenter\src>\local\jdk-1.8.0\bin\java MyXmlToUser UserError1.xml
Unmarshal XML file to user object...
My user object:
   Name: Frank Y. Ivy
   BirthDate: null
   Sex: Male
   ID: 2

2. Data parsing exception example - Create the following invalid XML file, UserError2.xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<User ID="two">
    <BirthDate>Unknown</BirthDate>
    <Name>Frank Y. Ivy</Name>
    <Sex>Male</Sex>
</User>

Run the MyXmlToUser.java program given in the previous tutorial. The Unmarshaller returns NumberFormatException for the invalid integer in the XML:

\fyicenter\src>\local\jdk-1.8.0\bin\java MyXmlToUser UserError2.xml
Exception in thread "main" java.lang.NumberFormatException: Not a number: two
   at com.sun.xml.internal.bind.DatatypeConverterImpl._parseInt(DatatypeConverterImpl.java:110)
   at com.fyicenter.demo.User_JaxbXducedAccessor_id.parse(TransducedAccessor_field_Integer.java:57)
   at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StructureLoader.startElement(StructureLoader.java:195)
...

 

Examples for JAXB (Java Architecture for XML Binding)

⇒⇒FAQ for jaxb-*.jar - Java Architecture for XML Binding

2017-06-30, 727👍, 0💬