Spring Tutorial - Spring Object-XML Mapping








The following code shows how to use Castor to do Java Object to XML Mapping.

Project Dependency

In order to use castor, add the following dependencies to pom.xml file.

    <properties>
    <spring.version>3.0.5.RELEASE</spring.version>
  </properties>

  <dependencies>

    <!-- Spring 3 dependencies -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- spring oxm -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- Uses Castor for XML -->
    <dependency>
      <groupId>org.codehaus.castor</groupId>
      <artifactId>castor</artifactId>
      <version>1.2</version>
    </dependency>

    <!-- Castor need this -->
    <dependency>
      <groupId>xerces</groupId>
      <artifactId>xercesImpl</artifactId>
      <version>2.8.1</version>
    </dependency>

  </dependencies>




Java Bean

Here is a simple Java bean for doing the xml mapping

package com.java2s.common;

public class Employee {

    String name;
    int age;
    boolean trained;
    String address;
    public String getName() {
      return name;
    }
    public void setName(String name) {
      this.name = name;
    }
    public int getAge() {
      return age;
    }
    public void setAge(int age) {
      this.age = age;
    }
    public boolean isTrained() {
      return trained;
    }
    public void setTrained(boolean trained) {
      this.trained = trained;
    }
    public String getAddress() {
      return address;
    }
    public void setAddress(String address) {
      this.address = address;
    }

}




Marshaller and Unmarshaller

The following code handles the mapping via Spring's oxm interfaces : Marshaller and Unmarshaller.

package com.java2s.common;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;

public class XMLConverter {

  private Marshaller marshaller;
  private Unmarshaller unmarshaller;

  public Marshaller getMarshaller() {
    return marshaller;
  }

  public void setMarshaller(Marshaller marshaller) {
    this.marshaller = marshaller;
  }

  public Unmarshaller getUnmarshaller() {
    return unmarshaller;
  }

  public void setUnmarshaller(Unmarshaller unmarshaller) {
    this.unmarshaller = unmarshaller;
  }

  public void convertFromObjectToXML(Object object, String filepath)
    throws IOException {

    FileOutputStream os = null;
    try {
      os = new FileOutputStream(filepath);
      getMarshaller().marshal(object, new StreamResult(os));
    } finally {
      if (os != null) {
        os.close();
      }
    }
  }

  public Object convertFromXMLToObject(String xmlfile) throws IOException {

    FileInputStream is = null;
    try {
      is = new FileInputStream(xmlfile);
      return getUnmarshaller().unmarshal(new StreamSource(is));
    } finally {
      if (is != null) {
        is.close();
      }
    }
  }

}

Spring Configuration

In Spring's bean configuration file, inject CastorMarshaller as the XML binding framework.

<beans 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-3.0.xsd">

  <bean id="XMLConverter" class="com.java2s.common.XMLConverter">
    <property name="marshaller" ref="castorMarshaller" />
    <property name="unmarshaller" ref="castorMarshaller" />
  </bean>
  <bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller" />

</beans>

Example

Here is the code run the application.

package com.java2s.common;

import java.io.IOException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class App {
  private static final String XML_FILE_NAME = "customer.xml";

  public static void main(String[] args) throws IOException {
    ApplicationContext appContext = new ClassPathXmlApplicationContext("SpringBeans.xml");
    XMLConverter converter = (XMLConverter) appContext.getBean("XMLConverter");

    Employee customer = new Employee();
    customer.setName("java2s");
    customer.setAge(99);
    customer.setTrained(true);
    customer.setAddress("This is address");

    //from object to XML file
    converter.convertFromObjectToXML(customer, XML_FILE_NAME);

    //from XML to object
    Employee customer2 = (Employee)converter.convertFromXMLToObject(XML_FILE_NAME);
    System.out.println(customer2);


  }
}

The code above generates the following result.

The following XML file "customer.xml" is generated in the project root folder.

File : customer.xml

<?xml version="1.0" encoding="UTF-8"?>
<customer trained="true" age="99">
  <address>This is address</address>
  <name>java2s</name>
</customer>


Download Castor_XML_Mapping.zip

Castor XML Mapping

To control which field should use as attribute or element, use Castor XML mapping file to define the relationship between Object and XML.

The following code creates the mapping file, mapping.xml. Put it into our project classpath.

<mapping>
  <class name="com.java2s.core.model.Employee">

    <map-to xml="customer" />

    <field name="age" type="integer">
      <bind-xml name="age" node="attribute" />
    </field>

    <field name="trained" type="boolean">
      <bind-xml name="trained" node="element" />
    </field>

    <field name="name" type="string">
      <bind-xml name="name" node="element" />
    </field>

    <field name="address" type="string">
      <bind-xml name="address" node="element" />
    </field>
  </class>
</mapping>

In Spring bean configuration file, inject above mapping.xml into CastorMarshaller via "mappingLocation".

<beans 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-3.0.xsd">

  <bean id="XMLConverter" class="com.java2s.core.XMLConverter">
    <property name="marshaller" ref="castorMarshaller" />
    <property name="unmarshaller" ref="castorMarshaller" />
  </bean>
  <bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller" >
    <property name="mappingLocation" value="classpath:mapping.xml" />
  </bean>

</beans>