package tryXStream;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import tryXStream.vo.Person;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class XMLToObject {
public static void main(String[] args) {
// Instantiate XStream Object
XStream xstream = new XStream(new DomDriver());
// Set Person class into xstream alias
xstream.alias("person", Person.class);
// Create a StringBuffer var
StringBuffer contents = new StringBuffer();
try {
// Set BufferReader var "in" to read from PersonXML.xml file
BufferedReader in = new BufferedReader(new FileReader(
"D:/java_projects/xStreamTryOut/PersonXML.xml"));
String str;
while ((str = in.readLine()) != null) {
contents.append(str);
}
in.close();
} catch (IOException e) {
System.out.println(e.toString());
}
// Checking the StringBuffer variable "contents"
System.out.println(contents);
String content = new String();
// Put all the contents from contents to String variable content --xstream.fromXML()takes
//only String
content = contents.toString();
// Convert content into XML and change and set to obj newPerson of class Person
Person newPerson = (Person)xstream.fromXML(content);
// Print out the newPerson properties
System.out.println("Person's name: " + newPerson.name);
System.out.println("Person's age: " + newPerson.age);
}
}
--------------------------------------------------------------------------------------------
Person.java
package tryXStream.vo;
public class Person {
public String name;
public int age;
public Person(String name1,int age1 ) {
this.name = name1;
this.age = age1;
}
}
Monday, January 26, 2009
Subscribe to:
Posts (Atom)