This is very useful for developers who are going to implement the XML base java solutions. Here I'm showing how to persist the simple java object to XML.
First I create the MyBean.java class.
[sourcecode language="java"]
package mysamples;
import java.util.ArrayList;
/**
*
* @author dinuka
*/
public class MyBean {
private String name = null;
private int age;
private ArrayList telephonNos;
public MyBean() {
telephonNos = null;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList getTelephonNos() {
return telephonNos;
}
public void setTelephonNos(ArrayList add) {
this.telephonNos = add;
}
public void print(){
System.out.println("Name :"+this.name);
System.out.println("Age :"+this.age);
for(Integer tp: telephonNos){
System.out.println("Tp :"+tp);
}
}
}
[/sourcecode]
BeanToXml.java this is a simple class to persist the above MyBean.java
[sourcecode language="java"]
package mysamples;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
/**
*
* @author dinuka
*/
public class BeanToXml {
public static void main(String[] args) {
try {
MyBean myWriteBean = new MyBean();
myWriteBean.setName("Tom");
myWriteBean.setAge(28);
ArrayList places = new ArrayList();
places.add(123456789);
places.add(623623828);
myWriteBean.setTelephonNos(places);
//Save the MyBean object to xml
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("MyBean.xml")));
encoder.writeObject(myWriteBean);
encoder.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
[/sourcecode]
Output - MyBean.xml
[...] Dinuka Malalanayake HomeAbout RSS ← Persist JAVA object to XML [...]
ReplyDelete[...] http://malalanayake.wordpress.com/2012/09/07/persist-java-object-to-xml/ Share this:TwitterFacebookLinkedInLike this:LikeBe the first to like this. Leave a comment [...]
ReplyDelete