Posted by & filed under Uncategorized.

This example has moved.

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.




  • Anonymous

    what a horrible mess this jaxb is.

  • 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

  • http://arsenalist.com 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.

  • 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

  • http://arsenalist.com 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.

  • sean

    Thanks,

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

  • http://farmvilletactics.info/farmville-need-neighbors-secret-tips-on-how-to-get-more-neighbors-in-farmville/ Farmville need neighbours

    Love the new look. I enjoyed the content. Thanks for the excellent writing.

  • http://www.onlinecasinobingogames.com/feed/ play bingo

    Hey great post! My mates and I are researching a term paper about play bingo and its due next Friday. I did some looking around at and found some useful info here also. Thanks for the information.

  • http://www.onlinecasinobingogames.com/category/bingo-news/ online bingo

    Hi this is extremely helpful. Ive been trying to find ways to engage readers more effectively and after reading your remarks I feel like I have a much better idea of how to drive more of a discussion on my posts regarding online bingo at .

  • http://www.onlinecasinobingogames.com/feed/ bingo games

    I must tell that I am impressed with your site. Top notch web site, master all the way, and very knowledgeable in this topic of bingo games. I will be happy if you mark my site at . I have recommended you to many people and will continue to make so.,

  • http://www.onlinecasinobingogames.com/bingo-history/ bingo online

    I must tell that I am impressed with your site. Top notch web site, master all the way, and very knowledgeable in this topic of bingo online. I will be happy if you mark my site at . I have recommended you to many people and will continue to make so.,

  • http://www.onlinecasinobingogames.com/2009/play-in-our-free-bingo-tournaments-and-win-cash-prizes/ bingo

    Hey interesting post! My mates and I are researching a term paper about bingo and its due next Friday. I did some looking around at and found some useful info here also. Thanks for the information.

  • http://www.onlinecasinobingogames.com/bingo-history/ online bingo

    Thank you, again, for putting this online bingo post together and for making all of our lives easier! I will apprize if you mark my site at .,

  • http://travelcoffeemugs.info/Keep-Coffee-Hot-with-a-Stainless-Steel-Travel-Coffee-Mug.html Stainless Steel travel coffee mugs

    Seems like that you have put a lot of effort and hard work into your post and I need additional of these on the net these days. I sincerely got a kick out of your post. I don’t really have significantly to say in response, I only wanted to comment to reply amazing work.

  • http://www.onlinecasinobingogames.com/feed/ bingo online

    Hey nice post! My fiends and I are researching a term paper about bingo online and its due next Friday. I did some looking around at and found some useful info here also. Thanks for the information.

  • http://bit.ly/slotocash Cristine Riverman

    You should definitely take advantage of the free $10 no deposit bonus at SlotoCash. Available now at: SlotoCash. Good luck!

  • http://surveyexchange.cn how to buy from taobao

    When i saw this trailer i wass amazed of the high quality and very realistyc effects. One of the best cg movie i ever see. Can w8 to see the warcraft movie

  • http://bit.ly/saturn-online Sarai Marksberry

    You should definitely take a look at the $25 no deposit bonus at Saturn Casino. It’s a great place to play.

  • http://www.plasticpond.net Charlie Wilson

    our local shop is giving away some free coffe mugs that are also of high quality,,*`

  • http://200mwlaser.net/ Danyell Fury

    This is a excellent facts, i was doing my homework for my thesis content and your article give us a few point which i can work with. Thanks.

  • http://www.melatoninfaq.com Lexie Wilkinson

    i always use Ceramic Coffee mugs because they are quite tough, i dropped them on the floor without breaking-,;

  • http://www.law-website.com/ law school

    You can not miss this.Please come to watch it.

  • http://www.melatoninfaq.com Melatonin 

    my favorite coffee mug are those that are made from porcelain or ceramic~;,

  • http://www.yourdomain123.com Sasha

    This really is getting a bit far more subjective, but I much like the Zune Marketplace. The interface is colorful, has a lot more flair, and some cool features like ‘Mixview’ that let you quickly see related albums, songs, or other users related to what you are listening to. Clicking on one of those will center on that item, and another group of “neighbors” will come into view, letting you navigate close to exploring by similar artists, songs, or users. Talking about users, the Zune “Social” is also great fun, letting you find others with shared tastes and achieving friends with them. After this you can listen to a playlist created depending on an amalgamation of what all your friends are hearing, also is enjoyable. Those worried about privacy will be relieved to understand you are able to prevent the public from seeing your personal listening habits should you so choose.

  • http://www.winding-machine.net Winding Machine ยท

    ceramic coffee mugs are the ones that i prefer to use because they last longer ..

  • http://ucanwatchmoviesonline.com Thomas Impson

    hi anyone, I was just checkin’ out this site and I really like the foundation of the article, and have nothing to do, so if anyone would like to to have an enjoyable convo about it, please contact me on myspace, my name is lisa polaska

  • http://www.naturalhemorrhoidtreatments.org Marinda Jerding

    I really glad to find this internet site on bing, just what I was searching for : D too saved to favorites .