how-to

Classes

How to serialize object instance into XML file

For this example you need:

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;

From JDK 1.4 is possible to serialize object instance into XML stream.

This type of serialization is useful for complicated JavaBeans and Swing components.

You must accept this rules:

STEP 1

Create class for serialization:

public class Person1  {
          
  public Person1() {}
      
  private String name;
  private int age;

  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public void setName(String name) {
    this.name = name;
  }       
}

STEP 2

Serialize class instance data into XML file:

/* -- create and fill class instance */
    
Person1 person = new Person1();
    
person.setName( "Jack Howard" );
person.setAge( 35 );
    
try {
  /* -- create XML serialization */
      
  XMLEncoder xml = new XMLEncoder( new FileOutputStream( "c:\\serialize.xml" ) );
      
  xml.writeObject( person );
      
  xml.close();
      
} catch (FileNotFoundException ex) {
  Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
}

Above code create this XML file.

STEP 3

For data deserialization call this code:

try {
  /* -- create XML deserialization */
      
  XMLDecoder xml = new XMLDecoder( new FileInputStream( "c:\\serialize.xml" ) );

  Person1 person = (Person1) xml.readObject();
      
  xml.close();
      
  /* -- show person data */
      
  System.out.println( person.getName() );
  System.out.println( person.getAge() );
      
} catch (FileNotFoundException ex) {
  Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
}

The output will be:

Jack Howard
35