RSS

Persist JAVA object to XML

07 Sep

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.

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);
 }
 }
}

BeanToXml.java this is a simple class to persist the above MyBean.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();
 }

}
}

Output – MyBean.xml

Advertisements
 
2 Comments

Posted by on September 7, 2012 in java

 

Tags: , , ,

2 responses to “Persist JAVA object to XML

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: