Sunday, February 17, 2013

Working with JAXB for binding XML

Here are a few snippets for binding Java objects to XML using JAXB.

Generating XML Schema from Java classes and vice versa

This snippet uses jaxb-maven-plugin to generate schema from a set of annotated Java classes. The second execution does the reverse, it generates Java classes from a schema. Additional configuration can be given using a binding file.

Marshalling using JAXB

In this snippet, an @XmlRootElement annotated class gets serialized to XML with a target namespace for all elements using Additional properties configure the marshaller for pretty-printing the XML and setting the location of the schema.

Unmarshalling using JAXB

In this snippet, Java class instances are populated from an XML document. The XML is validated against a schema in the process.

Customizing generated classes

Generated classes can be customized in several ways. For instance, generated classes can be prefixed and suffixed so that they don't clash with existing classes. This is done by creating a binding file as illustrated below. Binding files are added to maven plugin configuration with bindingDirectory and bindingFiles tags.

Further Reading

No comments:

Post a Comment