This Java tip demonstrates a method of serializing a bean to XML. A Bean persists by having its properties, fields, and state information saved and restored to and from storage. The mechanism that makes persistence possible is called serialization. JavaBeans uses the JDK's object serialization API for its serialization needs.

  // Create an object and set properties
    MyClass obj = new MyClass();
    obj.setProps(new int[]{1, 2, 3});
    try {

        // Serialize object into XML
        XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
            new FileOutputStream("outfilename.xml")));

    } catch (FileNotFoundException e) {

    // This class defines two properties - prop and props
    public class MyClass {

        // The prop property
        int i;
        public int getProp() {
            return i;
        public void setProp(int i) {
            this.i = i;
        // The props property
        int[] iarray = new int[0];

        public int[] getProps() {
            return iarray;
        public void setProps(int[] iarray) {
            this.iarray = iarray;

    <?xml version="1.0" encoding="UTF-8"?>
    <java version="1.4.0" class="java.beans.XMLDecoder">
        <object class="MyClass">
            <void property="prop">
            <void property="props">
                <array class="int" length="3">
                    <void index="0">
                    <void index="1">
                    <void index="2">

Here is the XML data: