Serialize an object using XMLTag(s): XML


Consider this simple class
public class Foo {
   private String foo ;
  
   public void setFoo(String s) {
     foo = s;
   }
   
   public String getFoo() {
     return foo;
   }
}

The java.beans package provides useful methods to save an object state into an XML file and easily read it back.

Here an Helper class for our Foo class.

import java.beans.XMLEncoder;
import java.beans.XMLDecoder;
import java.io.*;

public class FooHelper {
    public static void write(Foo f, String filename) throws Exception{
        XMLEncoder encoder =
           new XMLEncoder(
              new BufferedOutputStream(
                new FileOutputStream(filename)));
        encoder.writeObject(f);
        encoder.close();
    }

    public static Foo read(String filename) throws Exception {
        XMLDecoder decoder =
            new XMLDecoder(new BufferedInputStream(
                new FileInputStream(filename)));
        Foo o = (Foo)decoder.readObject();
        decoder.close();
        return o;
    }
}

Here how to use it.

public class FooTest {
    public static void main (String [] args) throws Exception{
        Foo  f1 = new Foo();
        f1.setFoo("bar");
        FooHelper.write(f1, "foo.xml");

        Foo f2 = FooHelper.read("foo.xml");
        System.out.println("Foo" + f2.getFoo());
        // the output : Foobar
    }
}
Just for fun, here the resulting XML file (with my installation)
<?xml version="1.0" encoding="UTF-8"?> 
<java version="1.5.0-beta" class="java.beans.XMLDecoder"> 
 <object class="Foo"> 
  <void property="foo"> 
   <string>bar</string> 
  </void> 
 </object> 
</JAVA>

blog comments powered by Disqus