JAXB2: XML to Java and vice-versa made easy

Remember the old days when you used to write a 150 line method which parsed your XML file into a Java class? Well that has long since been history. The next generation version of the JAXB XML processor, appropriately named JAXB2 has taken the liberty to make XML to Java conversion straightforward. Converting Java objects to XML has also been reduced to something trivial. Given an XSD, JAXB2’s XJC tool generates Java classes corresponding to your XSD Schema. Once you have the Java classes generated, reading and writing XML is a breeze.

The ONJava article by Deepak Vohra talks about this conversion process with JAXB. JAXB2 makes the process even easier as it generates fewer Java classes making the API calls even more intuitive. Marshalling and unmarshalling Java objects becomes dead simple.

The JAXB2 RI comes bundled with the Java Web Services Developers Pack 2.0

Given the following XSD, running the XJC command generates four Java files.

<xsd:schema
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <xsd:element name="catalog" type="catalogType"/>
 <xsd:complexType name="catalogType">
  <xsd:sequence>
   <xsd:element ref="journal"  minOccurs="0"
		maxOccurs="unbounded"/>
  </xsd:sequence>
  <xsd:attribute name="section" type="xsd:string"/>
  <xsd:attribute name="publisher" type="xsd:string"/>
 </xsd:complexType>
 <xsd:element name="journal" type="journalType"/>
 <xsd:complexType name="journalType">
  <xsd:sequence>
   <xsd:element ref="article"  minOccurs="0"
                       maxOccurs="unbounded"/>
  </xsd:sequence>
 </xsd:complexType>
 <xsd:element name="article" type="articleType"/>
 <xsd:complexType name="articleType">
  <xsd:sequence>
   <xsd:element name="title" type="xsd:string"/>
   <xsd:element name="author" type="xsd:string"/>
  </xsd:sequence>
  <xsd:attribute name="level" type="xsd:string"/>
  <xsd:attribute name="date" type="xsd:string"/>
 </xsd:complexType>
</xsd:schema>

c:\Sunjwsdp-2.0jaxbbinxjc -p my.package schema.xsd

  • ArticleType.java
  • CatalogType.java
  • JournalType.java
  • ObjectFactory.java

ArticleType, CatalogType and JournalType correspond to the complex types defined in the schema. ObjectFactory is the object creation class which is used to create instances of the other objects. The one alteration that is needed is to add the @XmlRootElement annotation to the CatalogType class.

Here’s some sample code that uses this API to create a nice enough XML File and then reads it back to Java objects:

JAXBContext jaxbContext=JAXBContext.
                 newInstance("my.package");
Marshaller marshaller=jaxbContext.
				createMarshaller();
ObjectFactory factory=new ObjectFactory();
CatalogType catalog=(CatalogType)
	(factory.createCatalogType());
catalog.setSection("my catalog");
catalog.setPublisher("my publisher");

ArticleType articleType =
			factory.createArticleType();
articleType.setAuthor("an author");
articleType.setTitle("a nice article");
articleType.setLevel("rant");

JournalType journal =
		factory.createJournalType();
journal.getArticle().add(articleType);

catalog.getJournal().add(journal);
File file = new File("c:/jaxb2example.xml");
marshaller.
	setProperty("jaxb.formatted.output", true);
marshaller.marshal(catalog,
		new FileOutputStream(file));

Unmarshaller unmarshaller =
		jaxbContext.createUnmarshaller();
CatalogType c = (CatalogType)
	unmarshaller.unmarshal(file);

System.out.println("author is = " +
		c.getJournal().get(0).getArticle().
		get(0).getAuthor());

The XML file that gets generated and read conforms to the XSD:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<catalogType section="my catalog"
			publisher="my publisher">
  <journal>
    <article level="rant">
      <title>a nice article</title>
      <author>an author</author>
    </article>
  </journal>
</catalogType>

The compilation and runtime requires the following JAR’s in the classpath:

c:\Sun\jwsdp-2.0\jaxb\lib\jaxb-api.jar
c:\Sun\jwsdp-2.0\jaxb\lib\jaxb-impl.jar
c:\Sun\jwsdp-2.0\jaxb\lib\jaxb-xjc.jar

Damn easy.

Advertisements

7 thoughts on “JAXB2: XML to Java and vice-versa made easy

  1. sivacham

    I have a schema that generates around 50 classes after i use the xjc batch file.The schema includes mandatory and optional elements.
    i have a query
    1)can i automate the creation of xml document.Since i hav a schema and i have a input driven interface ie i configure the values of the elements dynamically can i bypass the usage of the java objects or can i use them more efficeintly depending on the input.This because i dont wnt to write a long code with all the setters and getters nad finally creating a XML document

    Reply
  2. arsenalist

    I don’t know a way of creating the XML without using the Java API.

    I think you’ll have to wrap the JAXB2 Java API around one of your own wrapper classes which only takes the subset of the elements/attributes that you need.

    Reply
  3. sean

    I keep getting this error on marshaller.marshal…

    Severity Description Resource In Folder Location Creation Time Id
    2 The project was not built since its build path is incomplete. Cannot find the class file for javax.xml.stream.XMLEventWriter. Fix the build path then try building this project jaxTesting April 11, 2007 4:28:03 PM 6617

    What am I missing

    Reply
  4. arsenalist

    This sounds like a classpath issue. Make sure when you include the following JARs in your classpath, you do so from these exact directory locations.

    c:\Sun\jwsdp-2.0\jaxb\lib\jaxb-api.jar
    c:\Sun\jwsdp-2.0\jaxb\lib\jaxb-impl.jar
    c:\Sun\jwsdp-2.0\jaxb\lib\jaxb-xjc.jar

    The reason being is that these three JARs have Manifest files which refer to jars located in the c:\Sun\jwsdp-2.0 hierarchy using ../.. syntax. So if you’re copying these three jars to another location and then putting then in your classpath, refer to them directly from this location. If you do want to copy them to another location, look at the Manifest files and copy the dependent JARs too.

    Reply
  5. sean

    Thanks,

    c:\Sun\jwsdp-2.0\sjsxp\lib\sjsxp.jar is also required if your not putting everything in your classpath.

    Reply
  6. Pingback: Arsenalist » Blog Archive » JAXB2: XML to Java and vice-versa made easy

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s