blog.dotkam.com stats

AddThis Social Bookmark Button

Map Objects to/from XML with Castor

object xml mapping

Mapping Objects to XML and back is called Marshalling / Unmarshalling, and it is widely used in technology of the 21st century. It is not that easy to send your friend an Object you created in Java/Python/Ruby/.Net/C++ etc.., but it is very easy to send a text file - right?

Since XML is just a simple text file - would not it be great if we can convert an Object to XML, send it to our friend, who could then read our XML back into an Object and “enjoy it”? Sure it would! :)

There are many tools that can help us do that, but the one which is recommended by many is called Castor. So here is a simple example on how to map an Object into xml (marshal it to XML):

By default Castor will marshal/unmarshal with “-” in between the words, so MyObject will get marshaled into “my-object”, since that is a default behavior.

In order to create a “custom look” for your object and fields, you would need to create a mapping file - which is really not all that difficult. Here is a great example from castor.org:

Let’s say you have a class OrderItem:

public class OrderItem {
 
private String id;
private Integer orderQuantity;
 
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getOrderQuantity() {
return orderQuantity;
}
public void setOrderQuantity(Integer orderQuantity) {
this.orderQuantity = orderQuantity;
}
}

normally, if you map it with Castor without any mapping file, you would get:

<?xml version="1.0" ?>
   <order-item>
      <id>12</id>
      <order-quantity>100</order-quantity>
   </order-item>

but what if you need to marshal it (map it) to something like this which is way more natural and more readable:

<?xml version="1.0" ?>
   <item identity="12">
      <quantity>100</quantity>
   </item>

then you need to create a very simple mapping file:

<class name="mypackage.OrderItem">
 
   <map-to xml="item"/>
 
      <field name="id" type="string">
         <bind-xml name="identity" node="attribute"/>
      </field>
 
      <field name="orderQuantity" type="integer">
         <bind-xml name="quantity" node="element"/>
      </field>
 
</class>

It is very simple - you map:

"OrderItem"         to         "item"
"id"                to         "identity" (and making it an attribute by: node="attribute")
"orderQuantity"     to         "quantity"

img source


You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

tell me something...
  1. (required)
  2. (valid email required)
  3. Captcha
  4. (required)