Castor – Mapping Java Object to XML & XML to Object

Castor is Java-to-XML data binding Java library.

castor-java-xml

Objective:

  • How to convert between Java & XML “marshal/un-marshal” using Castor XML?

Environment & Libraries:

  • Eclipse
  • Maven

Libraries:

  • Castor
<dependency>
        <groupId>org.codehaus.castor</groupId>
        <artifactId>castor</artifactId>
        <version>1.2</version>
    </dependency>
     <dependency>            
         <groupId>xerces</groupId>            
         <artifactId>xercesImpl</artifactId>            
         <version>2.8.1</version>        
     </dependency>

 ( 1 ) Java Object “Article.java”

We want to convert objects of this class to XML and converted back to Java objects.

package com.hmkcode.vo;

import java.util.LinkedList;
import java.util.List;

public class Article {

	private String title;
	private String url;
	private List<String> categories;
	private List<String> tags;

        //getters, setters & toString
}

( 2 ) Convert Object to XML and XML to Object “Default Mapping”

Here is sample code to implement the conversion. Castor will bind data using default mapping.

package com.hmkcode;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;

import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;

import com.hmkcode.vo.Article;

public class App 
{
    public static void main( String[] args )
    {

    	try {

	    	//( 1 ) OBJECT --> XML
    		FileWriter writer = new FileWriter("article.xml");
			Marshaller.marshal(createArticle(), writer);
			writer.close();

	    	//( 2 ) XML --> OBJECT
			FileReader reader = new FileReader("article.xml");
			Article article = (Article) Unmarshaller.unmarshal(Article.class, reader);

			System.out.println(article);

		} catch (IOException e) {
			e.printStackTrace();
		} catch (MarshalException e) {
			e.printStackTrace();
		} catch (ValidationException e) {
			e.printStackTrace();
		}

    }

    public static Article createArticle(){
    	Article article = new Article();

    	article.setTitle("Castor - Java Object to XML & XML to Object Mapping");
    	article.setUrl("http://hmkcode.com/castor-java-object-xml");
    	article.addCategory("Java");
    	article.addTag("Java");
    	article.addTag("Castor");
    	article.addTag("XML");
    	article.addTag("Marshalling");
    	article.addTag("Unmarshalling");

    	return article;
    }
}

generated article.xml

<?xml version="1.0" encoding="UTF-8"?>
<article>
	<categories xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="java:java.lang.String">Java</categories>
	<tags xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="java:java.lang.String">Java</tags>
	<tags xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="java:java.lang.String">Castor</tags>
	<tags xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="java:java.lang.String">XML</tags>
	<tags xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="java:java.lang.String">Marshalling</tags>
	<tags xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="java:java.lang.String">Unmarshalling</tags>
	<url>http://hmkcode.com/castor-java-object-xml</url>
	<title>Castor - Java Object to XML &amp; XML to Object Mapping</title>
</article>

( 3 ) Convert Object to XML and XML to Object “With Mapping”

If you need a customized mapping we can provide Castor with user-defined mapping in form of xml.

  • mapping.xml
<?xml version="1.0"?><!DOCTYPE mapping PUBLIC "-//EXOLAB/Castor Mapping DTD Version 1.0//EN"                         
"http://castor.org/mapping.dtd">
<mapping>     
	<class name="com.hmkcode.vo.Article">                 
		<map-to xml="article" />                 
		<field name="title" type="string">            
			<bind-xml name="title" node="attribute"/>        
		</field>
		<field name="url" type="string">            
			<bind-xml name="url" node="element"/>        
		</field>                  
		<field name="categories" type="string" collection="arraylist">             
			<bind-xml name="category" />        
		</field>             
		<field name="tags" type="string" collection="arraylist">             
			<bind-xml name="tag" />        
		</field>
	</class>
</mapping>
package com.hmkcode;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
import org.exolab.castor.xml.XMLContext;

import com.hmkcode.vo.Article;

public class AppMapping 
{
    public static void main( String[] args )
    {

    	try {
        	//Load Mapping
        	Mapping mapping = new Mapping();
			mapping.loadMapping("mapping.xml");
			XMLContext context = new XMLContext();
	    	context.addMapping(mapping);

	    	//( 1 ) OBJECT --> XML

	    	//1.1 Prepare file writer 
	    	Writer writer = new FileWriter("mapped_article.xml");

	    	//1.2 Create a new Marshaller
	    	Marshaller marshaller = context.createMarshaller();
	    	marshaller.setWriter(writer);

	    	//1.3 Marshal "map" to xml
	    	marshaller.marshal(createArticle());

	    	//1.4
	    	writer.close();

	    	//( 2 ) XML --> OBJECT

	    	//2.1 Prepare file writer 
	    	Reader reader = new FileReader("mapped_article.xml");

	    	//2.2 Create a new Unmarshaller
	    	Unmarshaller unmarshaller = context.createUnmarshaller();
	    	unmarshaller.setClass(Article.class);

	    	//2.3 Unmarshal "map" to Object
	    	Article article = (Article) unmarshaller.unmarshal(reader);

	    	//2.4 
	    	reader.close();

	    	System.out.println(article);

		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (MappingException e1) {
			e1.printStackTrace();
		} catch (MarshalException e) {
			e.printStackTrace();
		} catch (ValidationException e) {
			e.printStackTrace();
		}
    }
    public static Article createArticle(){
    	Article article = new Article();

    	article.setTitle("Castor - Java Object to XML & XML to Object Mapping");
    	article.setUrl("http://hmkcode.com/castor-java-object-xml");
    	article.addCategory("Java");
    	article.addTag("Java");
    	article.addTag("Castor");
    	article.addTag("XML");
    	article.addTag("Marshalling");
    	article.addTag("Unmarshalling");

    	return article;
    }
}

generated mapped_article.xml

<?xml version="1.0" encoding="UTF-8"?>
<article title="Castor - Java Object to XML &amp; XML to Object Mapping">
	<url>http://hmkcode.com/castor-java-object-xml</url>
	<category>Java</category>
	<tag>Java</tag>
	<tag>Castor</tag>
	<tag>XML</tag>
	<tag>Marshalling</tag>
	<tag>Unmarshalling</tag>
</article>

Soruce Code @ GitHub