How do I write a JavaBean to an XML file using XMLEncoder?
Author: Deron Eriksson
Description: This Java tutorial shows how to write a JavaBean to an XML file using Java's XMLEncoder class.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


Page:    1 2 >

The XMLEncoder class makes it easy to 'serialize' a JavaBeanW object to an XMLW file. One great benefit of this form of serializationW is that you can readily view the JavaBean data in its saved form. You can also modify the data in the file via a text or XML editor.

The XmlEncodeToFile class demonstrates this. It creates a MyBean object and sets several values in it. It instantiates an XMLEncoder object and has an output stream to the "mybean.xml" file. We write the MyBean object to the "mybean.xml" file via the XMLEncoder.write() method. We then call the close() method on XMLEncoder.

XmlEncodeToFile.java

package example;

import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.util.Vector;

public class XmlEncodeToFile {

	public static void main(String[] args) throws Exception {

		MyBean mb = new MyBean();
		mb.setMyBoolean(true);
		mb.setMyString("xml is cool");
		Vector<String> v = new Vector<String>();
		v.add("one");
		v.add("two");
		v.add("three");
		mb.setMyVector(v);

		FileOutputStream fos = new FileOutputStream("mybean.xml");
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		XMLEncoder xmlEncoder = new XMLEncoder(bos);
		xmlEncoder.writeObject(mb);
		xmlEncoder.close();

	}

}

The MyBean class is shown here:

MyBean.java

package example;

import java.io.Serializable;
import java.util.Vector;

public class MyBean implements Serializable {

	private static final long serialVersionUID = 1L;
	private boolean myBoolean;
	private String myString;
	private Vector<String> myVector;

	public MyBean() {
	}
	public boolean isMyBoolean() {
		return myBoolean;
	}
	public void setMyBoolean(boolean myBoolean) {
		this.myBoolean = myBoolean;
	}
	public String getMyString() {
		return myString;
	}
	public void setMyString(String myString) {
		this.myString = myString;
	}
	public Vector<String> getMyVector() {
		return myVector;
	}
	public void setMyVector(Vector<String> myVector) {
		this.myVector = myVector;
	}
}

(Continued on page 2)

Page:    1 2 >