Serializing objects to XML

14 / May / 2010 by Anshul Sharma 2 comments

XStream is a simple Java library to serialize objects to XML and back again.
Suppose we have a Person class as follows:

  public class Person {
  private String name
  private int age
  private Address address
}

public class Address {
  private String street
  private String city
  private String state
  private String country
}
 

The following code will convert instance to XML:

XStream xstream = new XStream();   // instantiate the XStream class
xstream.alias("person", Person.class);  //the alias will be the root node.

Person personInstance = new Person()
// populate the person object

String xml = xstream.toXML(personInstance) 

XML will look like :


  
    
    

To reconstruct an object, from the XML:

Person person = (Person)xstream.fromXML(xml) 

Hope this helpled!

Cheers!

Anshul Sharma

FOUND THIS USEFUL? SHARE IT

comments (2)

Leave a Reply

Your email address will not be published. Required fields are marked *