Java

XML Serialization of Java Objects

To serialize a Java object to XML you need XMLEncoder class.

Let’s see an example!

1. Create a Customer class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Customer {
    private String _firstName;
    private String _lastName;
 
    public Customer(){
        this._firstName = "";
        this._lastName = "";
    }
 
    public String getFirstName() { 
        return this._firstName; 
    }
 
    public String getLastName() { 
        return this._lastName; 
    }
 
    public void setFirstName(String value) { 
        this._firstName = value; 
    }
 
    public void setLastName(String value) { 
        this._lastName = value; 
    }
 
    @Override
    public String toString(){
        return "Customer: " + this._lastName + ", " + this._firstName;
    }
}

2. Create the XMLSerializer class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.beans.XMLEncoder;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class XMLSerializer {
    public static void serialize(Customer c, String file){
        try {
            FileOutputStream os = new FileOutputStream(file); 
            XMLEncoder encoder = new XMLEncoder(os);
            encoder.writeObject(c);
            encoder.close();
            os.close();
        } catch (FileNotFoundException ex) {
            System.err.println(ex.getMessage());
        }
        catch (IOException io) {
            System.err.println(io.getMessage());
        }
    }
}

3. Run it

1
2
3
4
5
6
7
8
public class TestXMLSerializer {
    public static void main(String[] args) {
        Customer c = new Customer();
        c.setFirstName("George");
        c.setLastName("Karpouzas");
        XMLSerializer.serialize(c, "/path/to/xml/gkarpouzas.xml");
    }
}

4. Open xml file

<java version="1.7.0_147-icedtea" class="java.beans.XMLDecoder">
 <object class="Customer">
  <void property="firstName">
   <string>George</string>
  </void>
  <void property="lastName">
   <string>Karpouzas</string>
  </void>
 </object>
</java>

5. happy coding..