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.

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>1.3.1</version>
<executions>
<execution>
<id>Generate Java</id>
<goals>
<goal>xjc</goal>
</goals>
<phase>generate-resources</phase>
<configuration>
<schemaDirectory>${project.basedir}/src/main/resources</schemaDirectory>
</configuration>
</execution>
<execution>
<id>GenerateSchema</id>
<goals>
<goal>schemagen</goal>
</goals>
<phase>generate-resources</phase>
<configuration>
<includes>
<include>info/turkmence/sozlukdb/entities/*.java</include>
</includes>
<outputDirectory>${project.build.directory}/schemas</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
view raw pom.xml hosted with ❤ by GitHub

Marshalling using JAXB

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

//WordList is a @XmlRootElement annotated class.
JAXBContext jaxbContext = JAXBContext.newInstance(WordList.class);
//Schema to validate against.
Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(new SAXSource(new InputSource(getClass().getClassLoader().getResourceAsStream("schema.xsd"))));
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://mysite.com/schema/v1/ xsd/schema.xsd");
marshaller.setSchema(schema);
marshaller.marshal(wordList, new File("wordlist.xml"));
@XmlSchema(namespace = "http://mysite.com/schema/v1/",
elementFormDefault = XmlNsForm.QUALIFIED,
xmlns = {
@XmlNs(namespaceURI = "http://mysite.com/schema/v1/", prefix = "")
})
package com.mysite.entities;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

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.

//WordList is a @XmlRootElement annotated class.
JAXBContext jaxbContext = JAXBContext.newInstance(WordList.class);
//Setting a Schema to validate against.
Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(new SAXSource(new InputSource(getClass().getClassLoader().getResourceAsStream("schema.xsd"))));
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setSchema(schema);
File inputFile; //initialize input file
WordList wordList = (WordList) unmarshaller.unmarshal(inputFile);

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.

<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/jaxb http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd"
version="2.1" jaxb:extensionBindingPrefixes="xjc">
<jaxb:bindings schemaLocation="../schema/dto.xsd" node="/xs:schema">
<jaxb:schemaBindings>
<jaxb:package name="com.annagurban.nazar.dto.v1"/>
<jaxb:nameXmlTransform>
<jaxb:elementName prefix="My" suffix="Dto"/>
<jaxb:typeName prefix="My" suffix="Dto"/>
</jaxb:nameXmlTransform>
</jaxb:schemaBindings>
</jaxb:bindings>
</jaxb:bindings>
view raw binding.xml hosted with ❤ by GitHub

Further Reading

No comments:

Post a Comment