How do I read a JavaBean from an XML file using JOX?
Author: Deron Eriksson
Description: This Java tutorial describes how to read a JavaBean from an XML file using JOX (Java Objects in XML).
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1


Page:    1 2 >

In another tutorial, we saw how we could use JOX (Java Objects in XMLW) to write a JavaBeanW to an XML file. JOX can be obtained from http://www.wutka.com/jox.html. In this lesson, we'll show how JOX can be used to read the data from an XML file into a JavaBean.

This tutorial will utilize the jox116.jar and dtdparser121.jar libraries and will use the same project from our other tutorial:

'testing' project

The JoxReadJavaBeanFromFile class contains our main method. It reads in the data from the jox-test.xml file and uses that to populate a TestBean object. The method then outputs the contents of the bean to standard output. For brevity, I won't describe the TestBean and TestBean2 classes since they are described in the other tutorial.

JoxReadJavaBeanFromFile.java

package test;

import java.io.FileInputStream;

import com.wutka.jox.JOXBeanInputStream;

public class JoxReadJavaBeanFromFile {

	public static void main(String[] args) {

		try {
			FileInputStream in = new FileInputStream("jox-test.xml");
			JOXBeanInputStream joxIn = new JOXBeanInputStream(in);
			TestBean testBean = (TestBean) joxIn.readObject(TestBean.class);

			System.out.println("testBean contents:");
			System.out.println("testBoolean: " + testBean.isTestBoolean());
			System.out.println("testString: " + testBean.getTestString());
			TestBean2[] testBean2Array = testBean.getTestBean2Array();
			for (int i = 0; i < testBean2Array.length; i++) {
				TestBean2 testBean2 = testBean2Array[i];
				System.out.println(" #" + (i + 1) + " testBean2 String 1: "
						+ testBean2.getTestBean2String1());
				System.out.println(" #" + (i + 1) + " testBean2 String 2: "
						+ testBean2.getTestBean2String2());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

TestBean is given here:

TestBean.java

TestBean2 is given here:

TestBean2.java

The jox-test.xml file consists of the following:

jox-test.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<JoxTest>
<testBean2Array>
<testBean2String1>alpha</testBean2String1>
<testBean2String2>beta</testBean2String2>
</testBean2Array>
<testBean2Array>
<testBean2String1>gamma</testBean2String1>
<testBean2String2>delta</testBean2String2>
</testBean2Array>
<testBoolean>true</testBoolean>
<testString>test bean says hi</testString>
</JoxTest>

(Continued on page 2)

Page:    1 2 >