Pradeep's Blog

Google

Tuesday, March 14, 2006

How to use Xstream to serialise and de-serialise

In order to use xstream you require xstream-[version].jar and xpp3-[version].jar in the classpath. These files can be downloaded from xstream.codehaus.org. The xpp3-[version] is an alternative to the JAXP DOM parser.
Once these files have been placed in your classpath, you are ready to use xstream.Consider a simple java class having only set methods for variables that it has.
Project.java
class project {
private String projectName;
private ArrayList classFiles = new ArrayList();
private ArrayList jarFiles = new ArrayList();
}

Xml File that has to be serialized into project.java:

<>
< projectName> test/projectName>
&ltfile>cyvis.java
<file>test2
&lt/classFiles>

<file>file1
test2
&lt/jarFiles>


Code to serialise:

String xml = readFile(xmlFileName);
//reads contents of the xml into a string.

XStream xstream = new XStream();
//to use xstream you need a instance of it.

xstream.alias("project", Project.class);
xstream.alias("file", String.class);

//setting alias is optional, but doing so your can have tags that are meaningful
//for example instead of project.class you can have project.

project = (Project) xstream.fromXML(xml);
//fills in the Project
Now something like project.getName() will return you the name that was given in the project.

0 Comments:

Post a Comment

<< Home