Post

Serialization to XML in Java



Introduction

XML (eXtensible Markup Language) is a widely-used format for representing structured data. It is both human-readable and machine-readable, making it an ideal choice for data interchange and storage. In Java, XML serialization involves converting the state of an object into an XML format, which can then be saved to a file, sent over a network, or otherwise processed. Deserialization is the reverse process, where an XML representation is converted back into an object.

Libraries for XML Serialization in Java

Several libraries and frameworks facilitate XML serialization in Java, including:

  • Java Architecture for XML Binding (JAXB)
    A standard library included in Java SE that allows for converting Java objects to XML and vice versa.
  • XStream
    A simple library to serialize objects to XML and back.
  • Jackson
    Primarily known for JSON processing but also supports XML serialization.

In this article, we will focus on JAXB, which is a standard part of the Java SE platform and provides a convenient and powerful way to handle XML serialization and deserialization.

Using JAXB for XML Serialization

Setup

JAXB is included in Java SE, so you don’t need to add any external libraries to use it. However, if you are using a module system, you may need to include the appropriate modules.

Annotations

JAXB uses annotations to define the mapping between Java objects and XML. The most commonly used annotations are:

  • @XmlRootElement
    Defines the root element of the XML document.
  • @XmlElement
    Defines the XML element corresponding to a field in the Java object.
  • @XmlAttribute
    Defines an XML attribute corresponding to a field in the Java object.
  • @XmlAccessorType
    Defines the default access type for fields or properties.

Example

Let’s go through an example to illustrate XML serialization with JAXB.

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

@XmlRootElement(name = "person")
@XmlAccessorType(XmlAccessType.FIELD)
public class Person {
    
    @XmlAttribute
    private int id;
    
    @XmlElement
    private String name;
    
    @XmlElement
    private int age;

    // Default constructor is required for JAXB
    public Person() {}

    public Person(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    // Getters and setters
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}

public class JAXBExample {

    public static void main(String[] args) {
        try {
            Person person = new Person(1, "John Doe", 30);

            // Create JAXB context
            JAXBContext context = JAXBContext.newInstance(Person.class);

            // Create marshaller
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            // Serialize to XML
            StringWriter writer = new StringWriter();
            marshaller.marshal(person, writer);
            String xmlString = writer.toString();
            System.out.println("Serialized to XML:");
            System.out.println(xmlString);

            // Deserialize from XML
            Unmarshaller unmarshaller = context.createUnmarshaller();
            Person deserializedPerson = (Person) unmarshaller.unmarshal(new StringReader(xmlString));
            System.out.println("Deserialized from XML:");
            System.out.println("ID: " + deserializedPerson.getId());
            System.out.println("Name: " + deserializedPerson.getName());
            System.out.println("Age: " + deserializedPerson.getAge());

        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

Explanation

  1. Annotations
    The Person class is annotated with @XmlRootElement, @XmlElement, and @XmlAttribute to define the mapping to XML elements and attributes.
  2. Serialization
    The JAXBContext is created for the Person class. The Marshaller is used to convert the Person object into an XML string.
  3. Deserialization
    The Unmarshaller is used to convert the XML string back into a Person object.

Advantages of XML Serialization

  • Readability
    XML is human-readable, making it easier to debug and understand.
  • Standardization
    XML is a widely-adopted standard, facilitating interoperability between different systems.
  • Flexibility
    XML can represent complex hierarchical data structures.

Disadvantages of XML Serialization

  • Performance
    XML parsing can be slower compared to binary formats.
  • Size
    XML is verbose, resulting in larger file sizes compared to binary formats.

Conclusion

XML serialization in Java provides a powerful way to convert objects to a human-readable format that can be easily stored, transmitted, and reconstructed. JAXB, a standard part of Java SE, offers a convenient way to handle XML serialization with the help of annotations. Understanding how to use JAXB for XML serialization and deserialization is crucial for developers working on applications that require human-readable data interchange formats.

© 2024 Java Tutorial Online. All rights reserved.