Serializing a Java object into XML

Representing a complex object graph into an XML is not easy and binary serialization happens much faster. If you still need to represent your Java objects in XML, you can use the package JSX, downloadable from http://www.freshmeat.net/projects/jsx.

Put JSX0.9.5.0.jar in your classpath and try out the following example.

Customer.java:

import java.util.*;
 
class Customer {
   private String name;
   private int age;
   private Vector addresses;
   private Hashtable phones;
 
   public Customer(String name, int age, Vector addresses, Hashtable phones) {
      this.name = name;
      this.age = age;
      this.addresses = (Vector) addresses.clone();   
      this.phones = (Hashtable) phones.clone();
   }
 
   public String toString() {
      StringBuffer s = new StringBuffer();
      s.append("Name = " + name + "n");
      s.append("Age  = " + age  + "n");
      s.append("addresses = " + addresses + "n");
      s.append("phones    = " + phones);
      return s.toString();
   }
}

MainOut.java:

import java.util.*;
import java.io.*;
import JSX.*;
 
public class MainOut
{
   public static void main(String []args) {
      String name = "Jefke McCann";
      int age = 24;
      Vector addresses = new Vector();
      addresses.add("43, 5th Ave. 59715, Bozeman, MT");
      addresses.add("Handelskaai 3, 1000 Brussels, Belgium");
      Hashtable phones = new Hashtable();
      phones.put("001 (406) 585-2345", "ISDN");
      phones.put("0032 (2) 219.28.39", "FAX");
 
      Customer cust = new Customer(name, age, addresses, phones);
 
      try {
         ObjOut out = new ObjOut(true, new FileWriter("test.xml"));
         out.writeObject(cust);
      }
      catch(IOException e) {
         e.printStackTrace();
      }
   }
}

MainIn.java:

import java.util.*;
import java.io.*;
import JSX.*;
 
public class MainIn
{
   public static void main(String []args) {
      try {
         ObjIn in = new ObjIn(new FileReader("test.xml"));
         Customer cust = (Customer) in.readObject();
         System.out.println(cust);
      }
      catch(ClassNotFoundException e) {
         e.printStackTrace();
      }
      catch(IOException e) {
         e.printStackTrace();
      }
   }
}

If you execute java MainOut, the following XML will be written to disk.
test.xml:

<? jsx version="1"?>
<Customer
 name="Jefke McCann"
 age="24">
  <java.util.Vector obj-name="addresses">
    <java.lang.String valueOf="43, 5th Ave. 59715, Bozeman, MT"/>
    <java.lang.String valueOf="Handelskaai 3, 1000 Brussels, Belgium"/>
  </java.util.Vector>
  <java.util.Hashtable obj-name="phones">
    <java.lang.String valueOf="001 (406) 585-2345"/>
    <java.lang.String valueOf="ISDN"/>
 
    <java.lang.String valueOf="0032 (2) 219.28.39"/>
    <java.lang.String valueOf="FAX"/>
  </java.util.Hashtable>
</Customer>

MainIn will read in test.xml and create a Customer object from it.