Introduction to Spring OXM

SHARE & COMMENT :

Introduction

Spring OXM stands for Spring Object XML Mappers and it is a module available in Spring to ease the mapping between java objects and XML documents. The module is extensible and hence it provides integration with various popular frameworks like Castor, JAXB, XmlBeans and XStream. In this article, we will see how to serialize and de-serialize java objects and xml documents using various frameworks with the help of Spring. If you are beginner for spring framework, please read our article on introduction to spring framework, spring aop, spring mvc and list of spring articles. Javabeat covers extensive articles on the spring framework. If you are interested in receiving the updates, please subscribe here.

also read:

Download Spring OXM Sample Code

Castor Integration

In this section, we will see how to integrate Castor XML framework in Spring with the help of an example. Let us assume a Mobile object whose class definition is given below.

package net.javabeat.articles.spring.oxm.castor;

public class Mobile {

	private String name;
	private String model;
	private double price;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getModel() {
		return model;
	}
	public void setModel(String model) {
		this.model = model;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
}

As one can see, the definition is pretty straight forward. It defines various properties on a mobile such as ‘name’, ‘model’ and ‘price’ and its equivalent getters and setters. We will see how to serialize java mobile objects to xml documents.
Castor defines an xml binding definition file which defines how a java object should be mapped to its xml equivalent. For example, consider the following xml binding definition file for the above java class.

<?xml version="1.0"?>
<mapping>
	<description>Description of the mapping</description>

	<class name="net.javabeat.articles.spring.oxm.castor.Mobile">
	   <map-to xml="mobile-device"/>
	   <field name="name" type="string">
	      <bind-xml name="name" node="attribute"/>
	   </field>
	   <field name="model" type="string">
	      <bind-xml name="model" node="element"/>
	   </field>
	   <field name="price" type="double">
	      <bind-xml name="price" node="element"/>
	   </field>
	</class>

</mapping>

As we can see in the above file, the class name ‘net.javabeat.articles.spring.oxm.castor.Mobile’ is mapped to xml element ‘mobile-device’ with the help of ‘map-to-xml’ element. The property ‘name’ is mapped to an attribute with the same name. However, the properties ‘model’ and ‘price’ are mapped to elements instead of attributes.

<?xml version="1.0" encoding="UTF-8"?>

<beans default-autowire="no"
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id = "castorMarshaller" class = "org.springframework.oxm.castor.CastorMarshaller">
<property name="mappingLocation" value="classpath:simple-mapping.xml" />
</bean>

</beans>

Go through the above context definition which defines the ‘CastorMarshaller’ instance. Marshalling and un-marshaling in Spring are represented through separate interfaces ‘Marshaller’ and ‘Unmarshaller’ in the package ‘org.springframework.oxm’. The class ‘CastorMarshaller’, though named as marshaller will do both marshalling and un-marshalling. One mandatory property of ‘CastorMarshaller’ is ‘mappingLocation’ which points to the xml file containing the binding definition.
Now, let us see the client program that makes use of Castor Marshaller.

package net.javabeat.articles.spring.oxm.castor;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.castor.CastorMarshaller;

public class OxmCastorTest {

	public static void main(String[] args) throws Exception {

		ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
		CastorMarshaller marshaller = (CastorMarshaller)context.getBean("castorMarshaller");

		testObjectToXml(marshaller);
		testXmlToObject(marshaller);
	}

	private static void testObjectToXml(CastorMarshaller marshaller) throws Exception{

		Mobile mobileObject = new Mobile();
		mobileObject.setName("Nokia");
		mobileObject.setModel("N8");
		mobileObject.setPrice(32323D);

		FileOutputStream outputStream = new FileOutputStream(new File("mobile.xml"));
		StreamResult xmlFileResult = new StreamResult(outputStream);

		marshaller.marshal(mobileObject, xmlFileResult);
	}

	private static void testXmlToObject(CastorMarshaller marshaller) throws Exception{

		FileInputStream inputStream = new FileInputStream(new File("mobile.xml"));
		StreamSource xmlFileSource = new StreamSource(inputStream);

		marshaller.setTargetClass(Mobile.class);
		Mobile mobileObject = (Mobile)marshaller.unmarshal(xmlFileSource);

		System.out.println("Name is " + mobileObject.getName());
		System.out.println("Model is " + mobileObject.getModel());
		System.out.println("Price is " + mobileObject.getPrice());
	}
}

In the above code, the ‘CastorMarshaller’ instance is loaded from the spring context and the method ‘testObjectToXml()’ attempts to convert a java object to a xml document by calling the marshall() method defined on the ‘CastorMarshaller’ class. The method accepts two parameters, the first one being the object to be marshaled and the second representing the ‘result’ of ‘javax.xml.transform.stream.StreamResult’. The result is written to a file called ‘mobile.xml’ whose content is given below.

<?xml version="1.0" encoding="UTF-8"?>
<mobile-device name="Nokia"><model>N8</model><price>32323.0</price>
</mobile-device>

Similarly in the ‘testXmlToObject()’ method, we have un-marshalled the xml document to java object by calling the ‘unmarshal()’ method.

JAXB Integration

In this section, we will see how to integrate JAXB functionality with Spring. JAXB stands for Java API for XML binding and it can be used to marshall and unmarshall XML documents with simplified configuration. Before JAXB 2.0, one has to define the binding definitions in a separate configuration file, now with JAXB 2.0 in place, it is even easier to define the binding definitions through standard Java annotations.
Have a look at the following class.

package net.javabeat.articles.spring.oxm.jaxb;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "employee")
public class Employee {

	private String id;
	private String name;
	private Department department;

	public Employee() {}

	public Employee(String id, String name){
		this.id = id;
		this.name = name;
	}

	@XmlElement(name = "empId")
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	@XmlElement(name = "empName")
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	@XmlElement(name = "department")
	public Department getDepartment() {
		return department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}
}

The above class defines the ‘Employee’ class with three properties namely ‘id’, ‘name’ and ‘department’. Note that the property ‘department’ is a composite object. Through the usage of the annotation ‘XmlRootElement’ we have specified that the root element will be ‘employee’. Similarly the properties ‘id’, ‘name’ and ‘department’ are mapped to xml elements ‘empId’, ‘empName’ and ‘department’ with the help of the annotation ‘XmlElement’.

package net.javabeat.articles.spring.oxm.jaxb;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "department")
public class Department {

	private String id;
	private String name;

	@XmlAttribute(name = "deptId")
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	@XmlElement(name = "deptName")
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

Similarly in the above class declaration, the ‘id’ is mapped to the xml attribute ‘deptId’ with the help of the annotation ‘XmlAttribute’, whereas the property ‘name’ is mapped to an xml element ‘deptName’ with the help of the annotation ‘XmlElement’.
Now, we will look into the spring configuration file for JAXB. For marshalling and un-marshalling purposes, we have to use the class ‘org.springframework.oxm.jaxb.Jaxb2Marshaller’. The mandatory property ‘classesToBeBound’ has to be defined which takes an array of java classes carrying the annotation definition.

<
<?xml version="1.0" encoding="UTF-8"?>

<beans default-autowire="no"
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id = "jaxbMarshaller" class = "org.springframework.oxm.jaxb.Jaxb2Marshaller">
		<property name = "classesToBeBound">
			<array>
				<value>net.javabeat.articles.spring.oxm.jaxb.Employee</value>
				<value>net.javabeat.articles.spring.oxm.jaxb.Department</value>
			</array>
		</property>
	</bean>

</beans>

Given below is the client program that makes use of the above model classes and the configuration.

package net.javabeat.articles.spring.oxm.jaxb;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.Marshaller;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;

public class OxmJaxbTest {

	public static void main(String[] args) throws Exception {

		ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");

		Jaxb2Marshaller jaxbMarshaller = (Jaxb2Marshaller)context.getBean("jaxbMarshaller");

		Map marshallerProperties = new HashMap();
		marshallerProperties.put(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		jaxbMarshaller.setMarshallerProperties(marshallerProperties);

		testObject2Xml(jaxbMarshaller);
		testXml2Object(jaxbMarshaller);

	}

	private static void testObject2Xml(Jaxb2Marshaller jaxbMarshaller) throws Exception{

		Department department = new Department();
		department.setId("IT");
		department.setName("IT Department");

		Employee employee = new Employee("12345", "Test Employee");
		employee.setDepartment(department);

		FileOutputStream outputStream = new FileOutputStream(new File("employee.xml"));
		StreamResult result = new StreamResult(outputStream);

		jaxbMarshaller.marshal(employee, result);
	}

	private static void testXml2Object(Jaxb2Marshaller jaxbMarshaller) throws Exception{

		FileInputStream inputStream = new FileInputStream(new File("employee.xml"));
		StreamSource source = new StreamSource(inputStream);

		Employee employee = (Employee)jaxbMarshaller.unmarshal(source);
		System.out.println("Emp Id is " + employee.getId());
		System.out.println("Emp Name is " + employee.getName());

		Department department = employee.getDepartment();
		System.out.println("Dept Id is " + department.getId());
		System.out.println("Dept Name is " + department.getName());
	}
}

In the above program, the method ‘testObject2Xml’ attempts to marshall the employee object by serializing its contents to the xml file ‘employee.xml’ and the method ‘testXml2Object’ unmarshalls the xml contents back to a java object. Given below is the sample output produced from the above program.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
    <department deptId="IT">
        <deptName>IT Department</deptName>
    </department>
    <empId>12345</empId>
    <empName>Test Employee</empName>
</employee>

Integration with XmlBeans

In this section, we will see how to integrate XmlBeans with Spring’s OXM framework. There are multiple ways indicating how XmlBeans framework can be used to parse and process XML contents. In this example, we will define an xml schema and will see how to generate the java model classes from the xml schema.

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/message" xmlns:tns="http://www.example.org/message" elementFormDefault="qualified">

<complexType name="message">
<sequence>
<element name="data" type="string" minOccurs="1"
maxOccurs="1">
</element>
<element name="senderId" type="string" minOccurs="1"
maxOccurs="1">
</element>
<element name="size" type="int" minOccurs="1"
maxOccurs="1">
</element>
<element name="messageType" type="tns:messageType" minOccurs="1" maxOccurs="1"></element>
</sequence>
</complexType>

<complexType name="messageType">
<sequence>
<element name="value" type="string"></element>
</sequence>
</complexType>
</schema>

Go through the above xml schema which defines a complex data structure called message. As one can see, we have defined four properties for a message namely the ‘data’, ‘senderId’, ‘size’ and the ‘messageType’. The ‘messageType’ is again a complex type that indicates the type of the message.
The next step is to generate the java model classes from the xml schema. We will see how to generate them with the help of SchemaCompiler class which is present in ‘org.apache.xmlbeans.impl.tool’ package. Have a look at the following code.

package net.javabeat.articles.spring.oxm.xmlbeans;

import org.apache.xmlbeans.impl.tool.SchemaCompiler;

public class CodeGenerator {

	public static void main(String[] args) {

		String[] params = new String[]{"scomp", "./bin/message.xsd"};
		SchemaCompiler.main(params);
	}
}

We are invoking the ‘scomp’ (which stands for schema compiler) by passing in the location of the xml schema file. Once the above program is run, you can see a jar file getting created in the current directory containing the java class definition for the model types ‘message’ and ‘messageType’.
Given below is the spring configuration file containing the definition for ‘XmlBeansMarshaller’. Similar to other Spring’s OXM Marshaller classes, this class will do the job of both marshalling and un-marshalling.

<?xml version="1.0" encoding="UTF-8"?>

<beans default-autowire="no"
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id = "xmlBeansMarshaller" class = "org.springframework.oxm.xmlbeans.XmlBeansMarshaller">
</bean>

</beans>

Have a look at the below client program. Note that this jar file that got generated from the schema compiler has to be referenced in the program’s class path before running it. Because the types are generated from the schema compiler, the preferred way to create an object for a type is to invoke the appropriate factory methods. For example, for the types ‘message’ and ‘messageType’, the respective factory methods are ‘MessageFactory.newInstance()’ and ‘MessageTypeFactory.newInstance()’.

package net.javabeat.articles.spring.oxm.xmlbeans;

import java.io.File;
import java.io.FileOutputStream;

import javax.xml.transform.stream.StreamResult;

import org.example.message.Message;
import org.example.message.MessageType;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.xmlbeans.XmlBeansMarshaller;

public class OxmXmlBeansTest {

	public static void main(String[] args) throws Exception{

		ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
		XmlBeansMarshaller marshaller = (XmlBeansMarshaller)context.getBean("xmlBeansMarshaller");

		testObjectToXml(marshaller);
	}

	private static void testObjectToXml(XmlBeansMarshaller marshaller) throws Exception{

		Message message = Message.Factory.newInstance();

		message.setData("Test message");
		message.setSenderId("test@test.com");
		message.setSize(12345);

		MessageType messageType = MessageType.Factory.newInstance();
		messageType.setValue("VIDEO");

		message.setMessageType(messageType);

		FileOutputStream outputStream = new FileOutputStream(new File("message.xml"));
		StreamResult xmlResult = new StreamResult(outputStream);

		marshaller.marshal(message, xmlResult);
	}
}

Once the program is run, it will generate an output similar to the following.

<?xml version="1.0" encoding="UTF-8"?>
<xml-fragment>
	<mes:data xmlns:mes="http://www.example.org/message">
		Test message
	</mes:data>
	<mes:senderId xmlns:mes="http://www.example.org/message">
		test@test.com
	</mes:senderId>
	<mes:size xmlns:mes="http://www.example.org/message">
		12345
	</mes:size>
	<mes:messageType xmlns:mes="http://www.example.org/message">
		<mes:value>
			VIDEO
		</mes:value>
	</mes:messageType>
</xml-fragment>

Integration with XStream

In the final section of this article, we will see how to integrate XStream XML framework with Spring. We will see in-depth details on the various mapping techniques available with XStream in this section. We will model the details of bill information pertaining to a customer in the example given below.

package net.javabeat.articles.spring.oxm.xmlbeans;

import java.util.Date;

public class BillDetail {

	private String serviceProvider;
	private String billNumber;
	private Date billGenerationDate;
	private Double billAmount;

	public String getServiceProvider() {
		return serviceProvider;
	}
	public void setServiceProvider(String serviceProvider) {
		this.serviceProvider = serviceProvider;
	}
	public String getBillNumber() {
		return billNumber;
	}
	public void setBillNumber(String billNumber) {
		this.billNumber = billNumber;
	}
	public Date getBillGenerationDate() {
		return billGenerationDate;
	}
	public void setBillGenerationDate(Date billGenerationDate) {
		this.billGenerationDate = billGenerationDate;
	}
	public Double getBillAmount() {
		return billAmount;
	}
	public void setBillAmount(Double billAmount) {
		this.billAmount = billAmount;
	}
}

The above model class captures the various elements of a bill like ‘serviceProvider’, ‘billNumber’, ‘billGenerationDate’ and ‘billAmount’. In the following section, we have modeled the bildetails class for a specific customer containing a set of bill information. Now let us see how to control the marshalling and un-marshalling process with XStream.

package net.javabeat.articles.spring.oxm.xmlbeans;

import java.util.LinkedHashSet;
import java.util.Set;

public class BillDetails {

	private String customerId;
	private Set billDetails;

	public BillDetails(){
		billDetails = new LinkedHashSet();
	}

	public String getCustomerId() {
		return customerId;
	}
	public void setCustomerId(String customerId) {
		this.customerId = customerId;
	}
	public Set getBillDetails() {
		return billDetails;
	}
	public void setBillDetails(Set billDetails) {
		this.billDetails = billDetails;
	}
}

In the below Spring configuration file, we have created different instances of XStreamMarshaller with different configurations for better illustrating the usage of XStream. We will see how the various configuration elements control the marshalling operation in the next section.

<?xml version="1.0" encoding="UTF-8"?>

<beans default-autowire="no"
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id = "xStreamMarshaller" class = "org.springframework.oxm.xstream.XStreamMarshaller">
</bean>

<bean id = "xStreamMarshaller2" class = "org.springframework.oxm.xstream.XStreamMarshaller">
<property name = "aliases">
<map>
<entry key = "billDetails" value = "net.javabeat.articles.spring.oxm.xmlbeans.BillDetails"/>
<entry key = "billDetail" value = "net.javabeat.articles.spring.oxm.xmlbeans.BillDetail"/>
</map>
</property>
</bean>

<bean id = "xStreamMarshaller3" class = "org.springframework.oxm.xstream.XStreamMarshaller">
<property name = "aliases">
<map>
<entry key = "billDetails" value = "net.javabeat.articles.spring.oxm.xmlbeans.BillDetails"/>
<entry key = "billDetail" value = "net.javabeat.articles.spring.oxm.xmlbeans.BillDetail"/>
</map>
</property>
<property name = "fieldAliases">
<map>
<entry key = "net.javabeat.articles.spring.oxm.xmlbeans.BillDetails.customerId" value = "custId"/>
<entry key = "net.javabeat.articles.spring.oxm.xmlbeans.BillDetail.serviceProvider" value = "provider"/>
<entry key = "net.javabeat.articles.spring.oxm.xmlbeans.BillDetail.billAmount" value = "amount"/>
<entry key = "net.javabeat.articles.spring.oxm.xmlbeans.BillDetail.billGenerationDate" value = "generationDate"/>
<entry key = "net.javabeat.articles.spring.oxm.xmlbeans.BillDetail.billNumber" value = "billId"/>
</map>
</property>
</bean>

<bean id = "billDetailConverter" class = "net.javabeat.articles.spring.oxm.xmlbeans.BillDetailConverter"/>

<bean id = "xStreamMarshaller4" class = "org.springframework.oxm.xstream.XStreamMarshaller">
<property name = "aliases">
<map>
<entry key = "billDetails" value = "net.javabeat.articles.spring.oxm.xmlbeans.BillDetails"/>
<entry key = "billDetail" value = "net.javabeat.articles.spring.oxm.xmlbeans.BillDetail"/>
</map>
</property>
<property name="converters">
<array>
<ref bean = "billDetailConverter"/>
</array>
</property>
</bean>
</beans>

The following client program needs a detailed explanation.

package net.javabeat.articles.spring.oxm.xmlbeans;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

import javax.xml.transform.stream.StreamResult;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.xstream.XStreamMarshaller;

public class OxmXStreamTest {

	public static void main(String[] args) throws Exception{

		ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");

		testObjectToXmlSimple(context);
		testObjectToXmlClassAlias(context);
		testObjectToXmlFieldAlias(context);
	}

	private static void testObjectToXmlSimple(ApplicationContext context) throws Exception{

		XStreamMarshaller marshaller = (XStreamMarshaller)context.getBean("xStreamMarshaller");

		BillDetails billDetails = getTestObject();

		FileOutputStream outputStream = new FileOutputStream(new File("bill-details-1.xml"));
		StreamResult xmlResult = new StreamResult(outputStream);

		marshaller.marshal(billDetails, xmlResult);
	}

	private static void testObjectToXmlClassAlias(ApplicationContext context) throws Exception{

		XStreamMarshaller marshaller = (XStreamMarshaller)context.getBean("xStreamMarshaller2");

		BillDetails message = getTestObject();

		FileOutputStream outputStream = new FileOutputStream(new File("bill-details-2.xml"));
		StreamResult xmlResult = new StreamResult(outputStream);

		marshaller.marshal(message, xmlResult);
	}

	private static void testObjectToXmlFieldAlias(ApplicationContext context) throws Exception{

		XStreamMarshaller marshaller = (XStreamMarshaller)context.getBean("xStreamMarshaller3");

		BillDetails message = getTestObject();

		FileOutputStream outputStream = new FileOutputStream(new File("bill-details-3.xml"));
		StreamResult xmlResult = new StreamResult(outputStream);

		marshaller.marshal(message, xmlResult);
	}
}

The method ‘testObjectToXmlSimple’ shows the simplified usage of the XStream Marshaller. The usage assumes sensible defaults and running the above method will produce an output similar to the following. Note that in the below output, the default root name becomes the fully qualified name of the class.

<net.javabeat.articles.spring.oxm.xmlbeans.BillDetails>
	<customerId>CUST-12345</customerId>
	<billDetails>
		<net.javabeat.articles.spring.oxm.xmlbeans.BillDetail>
			<serviceProvider>Airtel</serviceProvider>
			<billNumber>TELE-12345</billNumber>
			<billGenerationDate>2011-03-12 15:55:46.952 IST</billGenerationDate>
			<billAmount>3445.0</billAmount>
		</net.javabeat.articles.spring.oxm.xmlbeans.BillDetail>
		<net.javabeat.articles.spring.oxm.xmlbeans.BillDetail>
			<serviceProvider>HDFC Insurance</serviceProvider>
			<billNumber>INSU-12345</billNumber>
			<billGenerationDate>2011-03-12 15:55:46.952 IST</billGenerationDate>
			<billAmount>54454.43</billAmount>
		</net.javabeat.articles.spring.oxm.xmlbeans.BillDetail>
		<net.javabeat.articles.spring.oxm.xmlbeans.BillDetail>
			<serviceProvider>Tata Indicom</serviceProvider>
			<billNumber>BROAD-12345</billNumber>
			<billGenerationDate>2011-03-12 15:55:46.952 IST</billGenerationDate>
			<billAmount>1700.0</billAmount>
		</net.javabeat.articles.spring.oxm.xmlbeans.BillDetail>
	</billDetails>
</net.javabeat.articles.spring.oxm.xmlbeans.BillDetails>

The second test method ‘testObjectToXmlClassAlias’ illustrates the class aliasing feature. This means that the class name can be aliased to a user defined name. This has been achieved because while defining the Marshaller instance in this case, we have included the property ‘aliases’ as shown below.

<property name = "aliases">
<map>
<entry key = "billDetails" value = "net.javabeat.articles.spring.oxm.xmlbeans.BillDetails"/>
<entry key = "billDetail" value = "net.javabeat.articles.spring.oxm.xmlbeans.BillDetail"/>
</map>
</property>

This means that the name ‘billDetails’ will be the alias for ‘net.javabeat.articles.spring.oxm.xmlbeans.BillDetails’ and similarly the name ‘billDetail’ will be the alias for ‘net.javabeat.articles.spring.oxm.xmlbeans.BillDetail’. Running the above test will result in the following output,

<billDetails>
	<customerId>CUST-12345</customerId>
	<billDetails>
		<billDetail>
			<serviceProvider>Airtel</serviceProvider>
			<billNumber>TELE-12345</billNumber>
			<billGenerationDate>2011-03-12 15:55:46.994 IST</billGenerationDate>
			<billAmount>3445.0</billAmount>
		</billDetail>
		<billDetail>
			<serviceProvider>HDFC Insurance</serviceProvider>
			<billNumber>INSU-12345</billNumber>
			<billGenerationDate>2011-03-12 15:55:46.994 IST</billGenerationDate>
			<billAmount>54454.43</billAmount>
		</billDetail>
		<billDetail>
			<serviceProvider>Tata Indicom</serviceProvider>
			<billNumber>BROAD-12345</billNumber>
			<billGenerationDate>2011-03-12 15:55:46.994 IST</billGenerationDate>
			<billAmount>1700.0</billAmount>
		</billDetail>
	</billDetails>
</billDetails>

The method ‘testObjectToXmlFieldAlias’ illustrates the usage of field aliasing, the corresponding XStream declaration now includes an additional property called ‘fieldAliases’ as shown below.

<property name = "fieldAliases">
<map>
<entry key = "net.javabeat.articles.spring.oxm.xmlbeans.BillDetails.customerId" value = "custId"/>
<entry key = "net.javabeat.articles.spring.oxm.xmlbeans.BillDetail.serviceProvider" value = "provider"/>
<entry key = "net.javabeat.articles.spring.oxm.xmlbeans.BillDetail.billAmount" value = "amount"/>
<entry key = "net.javabeat.articles.spring.oxm.xmlbeans.BillDetail.billGenerationDate" value = "generationDate"/>
<entry key = "net.javabeat.articles.spring.oxm.xmlbeans.BillDetail.billNumber" value = "billId"/>
</map>
</property>

Running the above program will generate the following output. As it can be seen, the property ‘customerId’ from the class ‘net.javabeat.articles.spring.oxm.xmlbeans.BillDetails’ has been aliased to the name ‘custId’. Similarly the properties ‘serviceProvider’, ‘billAmount’, ‘billGenerationDate’ and ‘billNumber’ from the class ‘net.javabeat.articles.spring.oxm.xmlbeans.BillDetail’ have been aliased to ‘provider’, ‘amount’, ‘generationDate’ and ‘billId’ respectively.

<billDetails>
	<custId>CUST-12345</custId>
	<billDetails>
		<billDetail>
			<provider>Airtel</provider>
			<billId>TELE-12345</billId>
			<generationDate>2011-03-12 15:55:47.18 IST</generationDate>
			<amount>3445.0</amount>
		</billDetail>
		<billDetail>
			<provider>HDFC Insurance</provider>
			<billId>INSU-12345</billId>
			<generationDate>2011-03-12 15:55:47.18 IST</generationDate>
			<amount>54454.43</amount>
		</billDetail>
		<billDetail>
			<provider>Tata Indicom</provider>
			<billId>BROAD-12345</billId>
			<generationDate>2011-03-12 15:55:47.18 IST</generationDate>
			<amount>1700.0</amount>
		</billDetail>
	</billDetails></billDetails>

Conclusion

This article provided in-depth coverage in explaining about the various XML frameworks that can be integrated with Spring through Spring’s Object XML framework. Plenty of code samples were given for better illustration. The various XML frameworks starting from Castor, JAXB, XMLBeans, XStream have different ways to deal with object marshalling and un-marshalling and Spring with its extensible nature has provided an unified way for integrating various XML framework models.
If you have any questions on the spring framework integration with OXM, please post it in the comments section. Also search in our website to find lot of other interesting articles related to the spring framework. There are some interesting articles about spring framework, interview questions, spring and hibernate integration,etc.

also read:

If you would like to receive the future java articles from our website, please subscribe here.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. Sajeev Ramakrishnan says:

    Very good article with simple explanation. Thank you :)

Trackbacks

  1. […] Introduction to Spring OXM […]

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better