Tutorials » Transmitting Data Between XML Documents and Java Beans

While working for one of my previous projects I came across a requirement where I wanted to transfer my XML data into Java Beans or objects. Many of you also might have faced same scenario. In this article I will show, how you can achieve this functionality using a set of Java libraries called JOX that makes it easy to transfer data between XML documents and Java Beans.

How JOX Works

JOX matches an XML document to the fields of a java bean and will use a DTD when writing an XML document if one is available. Because JOX identifies the Java Bean at runtime, you can transmit XML into different classes.

Other approaches to achieve this functionality are using KBML (Koala Bean Markup Language) and Quick/JXML suite of libraries. KBML has <property> and <value> tags. Quick/JXML gives you the same XML document flexibility as JOX. Only price you pay is that you must use a special schema language called QJML to describe the mapping between XML and Java. With JOX, for e.g. if I have an Address bean that has addressLine1 and addressLine2 properties. You could read in an XML file containing <address-line1> and <address-line2> properties. JOX lets you use any form of XML document and any Java Bean, and you don’t have to create a separate schema to describe the mapping between Java and XML like JXML. This way JOX differs from other two libraries.

JOX has following rules, which need to be followed while using:

  • You must use Java Bean (getter/setter methods) because JOX uses introspection to understand the property names.
  • XML tag names must match bean property names. The XML tag
    <address-Line1> will map successfully to addressLine1, address_line1.
  • JOX converts XML data to the type of the bean property.
  • Without a DTD, JOX uses bean property names as XML tag names.

JOX is an instant to use and you don’t have to learn any new language or format. JOX readers and writers rip open on to Input/Output Streams, Readers and Writers so you can use them with existing Java IO streams. JOX can also write a bean to a DOM object so we can pass it to the XSLT processor.

Following example shows how to transmit XML data into Java Bean. Here is the XML file sample.xml, from which we will transmit data to Java Bean.

<?xml version="1.0"?>
<SampleRoot>
<colors>red</colors>
<colors>yellow</colors>
<colors>green</colors>
<colors>orange</colors>
<value>44</value>
<price>75</price>
<firstName>Vikas</firstName >
</SampleRoot>

Now as I mentioned, you need to create a Bean with getter/setter methods. Also keep in mind that XML tag names must match bean property names.

For e.g. following are the bean methods (from SampleTest.Java) for tags <value> and <price> respectively.

public int getValue(){
   return value;
}
public void setValue(int aValue){
   value = aValue;
}
public int getPrice(){
   return price;
}

Now TransmitXml.java reads in the XML file and stores its values into SampleBean.

import com.wutka.jox.JOXBeanInputStream;
import java.io.FileInputStream;

JOXBeanInputStream is An InputStream filter that reads XML into a bean. When you read an XML document, you must supply either a class or an object instance. The input stream will attempt to match XML tags to bean attributes in the class/object you supply.

If you supply a class, the input stream will automatically create a new object instance to hold the data.

The stream understands the basic Java data types and their object equivalents, plus strings and dates. Anything else must be a bean. It can also read arrays of any of the supported types or of beans if it tries to read a bean with an indexed property.

If there are XML fields that don't match the bean, it will ignore them. If the data types are not compatible, you will get an exception. At some point the stream will be smart enough to skip over incompatible fields.

public class TransferXml{
    public static void main(String[] args){
      try{
        FileInputStream fIn = new FileInputStream("sample.xml");

        JOXBeanInputStream joIn = new JOXBeanInputStream(fIn);

        SampleTestBean testBean = (SampleTestBean)         joIn.readObject(SampleTestBean.class);


        System.out.println(testBean.getFirstName());
        System.out.println(testBean.getPrice());
        String colors[] = testBean.getColors();
        for(int i=0;i<colors.length; i++){
          System.out.println(colors[i]);
        }

      }
      catch (Exception ex){
        ex.printStackTrace();
      }
    }
}

Note: Before running the code, download JOX from http://sourceforge.net/projects/jox and put jox116.jar file into classpath so that the java code can find corresponding classes at compile and run time.

JOX understands all the Java primitive types (byte, char, short, int, long, float, double and boolean) and the object-wrapper versions of those types (Byte, Character, Short, etc.). It also understands java.util.Date and String types. If a property is a nested object, it tries to match the nested XML to the nested object. JOX understands indexed properties, too, so it essentially supports arrays.

This way effortlessly you can transmit XML data into Java Beans for any kind of Java application.

 

About the Author

Vikas Pandya is a Sun-certified Java software engineer. He currently works as an XML/XSL, Java developer for Bank of America. He writes articles on Java, XML and related technologies for different sites. He also consults for Exedem Technology, focusing on XML Web Services and related technologies. Contact him at vikasdp@yahoo.com or vikas.pandya@exedem.com. Vikas Pandya