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;

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

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

Here how to use it.

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

        Foo f2 ="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"> 

blog comments powered by Disqus