Java Bean To XML Data Conversion in Java

Best and Easy Way to convert java object to XML Using XStream
keyword : Java Object to XML

XStream :

Stream is a simple library to serialize objects to XML and back again. 
Download XStream Jar :  http://xstream.codehaus.org/download.html 

Syntax :

For Object Creation:

XStream xStream = new XStream();

XML Conversion:

xStream.toXML(Object)

Clear Example:

Consider Bean Employee:

private static class Employee {
private String ename;
private String eno;
private String eaddress;

public Employee() {
}

public Employee(String ename, String eno, String eaddress) {
this.ename = ename;
this.eno = eno;
this.eaddress = eaddress;
}

public String getEaddress() {
return eaddress;
}

public void setEaddress(String eaddress) {
this.eaddress = eaddress;
}

public String getEname() {
return ename;
}

public void setEname(String ename) {
this.ename = ename;
}

public String getEno() {
return eno;
}

public void setEno(String eno) {
this.eno = eno;
}

Conversion Main Class Example

public static void main(String[] args) {
      XStream xStream = new XStream();
      Employee employee = new Employee("God", "01", "Earth");
      System.out.println(
              "Get XML:" + xStream.toXML(employee));
   }

Sample Output:

<com.thiyagaraaj.Employee>
  <ename>God</ename>
  <eno>01</eno>
  <eaddress>Earth</eaddress>
</com.thiyagaraaj.Employee>

Note : Here, Package comes for root tag. but we can change it.

Alias For Class Name:

Add these line, you can get XML without Package Name
xStream.alias("Employee", Employee.class);

Main Class Example for Change Root Tag Name

public static void main(String[] args) {
XStream xStream = new XStream();
xStream.alias("Employee", Employee.class);
Employee employee = new Employee("God", "01", "Earth");
System.out.println(
"Get XML:" + xStream.toXML(employee));
}

Sample Output:

Get XML:<Employee>
  <ename>God</ename>
  <eno>01</eno>
  <eaddress>Earth</eaddress>
</Employee>

Now you can get clear XML
More Information : http://xstream.codehaus.org/