I found a great tool called XStream that can generate Java objects directly from the XML. Previously, I used XMLBeans but this requires the XMLSchema to be generated. Moreover, installation process is bit hard. But with XStream, its pretty easy to create java objects from XMLs and getting XMLs from objects. Here I provide complete example, which is the extension of the code given in XStream's official site.
Requirements:
Three Files: XstreamTest.java , Person.java, PhoneNumber.java
Library: xstream-1.4.3.jar
JDK: 1.6xxx
1. XstreamTest.java
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
public class XstreamTest {
/**
* @param args
*/
public static void main(String[] args) {
Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
XStream xstream = new XStream(new StaxDriver());
String xml = xstream.toXML(joe);
System.out.println(xml);
Person p1 = (Person)xstream.fromXML(xml);
System.out.println("Phone no:"+p1.getPhone().getNumber());
}
}
2. Person.java
public class Person {
private String firstname;
private String lastname;
private PhoneNumber phone;
private PhoneNumber fax;
public Person(String fname,String lname){
this.firstname=fname;
this.lastname=lname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public PhoneNumber getPhone() {
return phone;
}
public void setPhone(PhoneNumber phone) {
this.phone = phone;
}
public PhoneNumber getFax() {
return fax;
}
public void setFax(PhoneNumber fax) {
this.fax = fax;
}
}
3. PhoneNumber.java
public class PhoneNumber {
private int code;
private String number
public PhoneNumber(int i, String string) {
this.code=i;
this.number=string;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
OUTPUT:
123
123
Phone no:1234-456