Serializing objects to XML
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
Thanks so much for the blog. Want more.
Say, you got a nice article post. Much obliged.