background image

The default JAXB Unmarshaller

<< Unmarshal Validate Example | Customizing JAXB Bindings >>
<< Unmarshal Validate Example | Customizing JAXB Bindings >>
34
U
SING
JAXB
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.UnmarshalException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.util.ValidationEventCollector;
import primer.po.*;
2. A
JAXBContext
instance is created for handling classes generated in
primer.po
.
JAXBContext jc = JAXBContext.newInstance( "primer.po" );
3. An
Unmarshaller
instance is created.
Unmarshaller u = jc.createUnmarshaller();
4. The default JAXB Unmarshaller
ValidationEventHandler
is enabled to
send to validation warnings and errors to
system.out
. The default config-
uration causes the unmarshal operation to fail upon encountering the first
validation error.
u.setValidating( true );
5. An attempt is made to unmarshal
po.xml
into a Java content tree. For the
purposes of this example, the
po.xml
contains a deliberate error.
PurchaseOrder po =
(PurchaseOrder)u.unmarshal(
new FileInputStream("po.xml"));
6. The default validation event handler processes a validation error, generates
output to
system.out
, and then an exception is thrown.
} catch( UnmarshalException ue ) {
System.out.println( "Caught UnmarshalException" );
} catch( JAXBException je ) {
je.printStackTrace();
} catch( IOException ioe ) {
ioe.printStackTrace();
Sample Output
Running
java Main
for this example produces the following output:
DefaultValidationEventHandler: [ERROR]: "-1" does not satisfy
the "positiveInteger" type
Caught UnmarshalException