analytics

Thursday, February 20, 2014

Object to Xml and Xml to Object Using Java XStream


This is very small but very useful code, if you run Junit test cases then it can very easily provide you java request object from XML request object. Again we write toString in object to get the object’s property information at run time, and to write toString we need to print all the properties. But if we can convert java object to String XML we can have all the object’s property values and that is very easy to read.

Xstream provides us API which converts the XML to object and object to XML again.
For this we have two dependencies jdom-1.1.jar and xstream-1.3.1.jar

Below code demonstrate the use of Xstream serialize and deserialize of an Customer object.
method getXMLToObject () converts Xml to Customer object and method getObjectToXML () converts Customer Object to Xml


package com.purejava4all;
import java.io.File;
import org.jdom.Document;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class XtreamUtil {

public static void main(String[] args) {
// Here we are reading Customer.xml file and converting that to Java Object
Customer customer = (Customer) getXMLToObject ("C:\\xmlfiles\\Customer.xml");
System.out.println("Xml to Customer \n" + customer);
// Once we have the java object we can use it in anywhere such as in test cases
// Here we are converting the java object again into XML String format
String customerXML = getObjectToXML (customer);                      
System.out.println("Customer to XML String\n" + customerXML);
}

public static T getXMLToObject(final String xmlFilePath) throws Exception {
                                final File file = new File(xmlFilePath);
                                if (!file.exists()) {
                                                throw new Exception("File doesn't exist at " + xmlFilePath);
                                }
                                final SAXBuilder builder = new SAXBuilder();
                                final Document doc = builder.build(file);
                                final String xml = new XMLOutputter().outputString(doc);
                                final XStream xstream = new XStream(new DomDriver());
                                final Object obj = xstream.fromXML(xml);
                                return (T) obj;
                }
               
public static String getObjectToXML(Object o){
        XStream xstream = new XStream();
        String xml = xstream.toXML(o);
        return xml;
                }

}

No comments:

Post a Comment