Saturday, April 14, 2012

How to get the XML String for a DTO (Data transfer object) using XStream

To get the XML for a DTO XStream (com.thoughtworks.xstream.XStream) is used, Download the "xstream-1.4.2.jar" jar : Click Here and add into your lib folder.

The Method which returns the XML for the passed DTO:
public static String getDTOasXML(Object dto){
 XStream xstream = new XStream();
        return xstream.toXML(dto);
}


The UserDto which needs to be converted to XML :

public class UserDto{

 
 private Long userId;

 private String userName;

 private String userEmail;

 public Long getUserId() {
  return userId;
 }

 public void setUserId(Long userId) {
  this.userId = userId;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }

 public String getUserEmail() {
  return userEmail;
 }

 public void setUserEmail(String userEmail) {
  this.userEmail = userEmail;
 } 
}

Note: Notice that the fields are private. XStream doesn't care about the visibility of the fields. No getters or setters are needed. Also, XStream does not limit you to having a default constructor.

The Test Class to implement the XStream.toXML() method :

package in.codeZila.test;

import in.codeZila.test.dto.UserDto;
import com.thoughtworks.xstream.XStream;


public class Test{
 
 /**
  * Using XStream method toXML():String to generate the XML for the passed DTO object
  * @param dto
  * @return dto XML as String
  */
 public static String getDTOasXML(Object dto){
  XStream xstream = new XStream();
  /**
   * Now, to make the XML outputted by XStream more concise, 
   * you can create aliases for your custom class names to XML 
   * element names. This is the only type of mapping required to 
   * use XStream and even this is optional.
   * 
   * Note: This is an optional step. Without it XStream would work fine, 
   * but the XML element names would contain the fully qualified name of 
   * each class (including package) which would bulk up the XML a bit.
   */
  xstream.alias("UserDto", UserDto.class);
  return xstream.toXML(dto);
 }
 
 public static void main(String[] args) {
  /**
   * Instantiate the UserDto and set its variables
   */
  UserDto userDto=new UserDto();
  userDto.setUserId(new Long(1));
  userDto.setUserName("CodeZila");
  userDto.setUserEmail("codezila@codezila.in");
  /**
   * Pass the userDto Object created above as getDTOasXML() argument
   */
  String dtoXml=Test.getDTOasXML(userDto);
  System.out.println(dtoXml);
 }
}



The Output XML :

Thats all, how simple XStream is!

Summary:

  • Create element name to class name aliases for any custom classes using xstream.alias(String elementName, Class cls); 
  • Convert an object to XML using xstream.toXML(Object obj); 
  • Convert XML back to an object using xstream.fromXML(String xml);


Your valuable inputs and suggestions are welcomed!