Saturday, 14 September 2019

How to convert an object into XML and XML into an object using JAXB? - BookStore Example

🚀 Master Java Programming with Ram N Java!

Subscribe now for comprehensive tutorials, clear code walkthroughs, and practical Java guides.

🔔 Subscribe to YouTube Channel

What is JAXB? (Java Architecture for XML Binding)

JAXB stands for Java Architecture for XML Binding. It provides a quick and convenient way to bind XML schemas and Java representations, making it easy for Java developers to read and write XML data without needing low-level XML parsers like DOM or SAX.

Key Concepts: Marshalling & Unmarshalling

Working with JAXB revolves around two fundamental operations:

  • Marshalling (Object to XML): The process of serializing a Java object tree into an XML document or stream.
  • Unmarshalling (XML to Object): The process of deserializing XML data back into a structured Java object.

Essential JAXB Annotations

To map your Java classes to XML structures, JAXB uses simple annotations:

  • @XmlRootElement: Defines the top-level root element of the XML document.
  • @XmlElement: Maps a Java field or getter/setter to an XML child tag.
  • @XmlAttribute: Maps a field as an attribute within an XML element.
  • @XmlElementWrapper: Generates a wrapper XML element around collection elements (such as a list of books).

Step-by-Step BookStore Example

1. Define the Book & BookStore Classes

Create your POJO classes and annotate them so JAXB knows how to convert the properties:

@XmlRootElement(name = "bookstore")
public class BookStore {
    private String name;
    private List<Book> bookList;

    @XmlElement(name = "name")
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    @XmlElementWrapper(name = "bookList")
    @XmlElement(name = "book")
    public List<Book> getBookList() { return bookList; }
    public void setBookList(List<Book> bookList) { this.bookList = bookList; }
}

2. Marshalling: Converting Java Object to XML

JAXBContext context = JAXBContext.newInstance(BookStore.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

// Write to console or file
marshaller.marshal(bookStore, System.out);

3. Unmarshalling: Converting XML to Java Object

JAXBContext context = JAXBContext.newInstance(BookStore.class);
Unmarshaller unmarshaller = context.createUnmarshaller();

BookStore bookStore = (BookStore) unmarshaller.unmarshal(new File("bookstore.xml"));
System.out.println("Store Name: " + bookStore.getName());

Recommended Java Tutorials from Ram N Java

No comments:

Post a Comment

Tutorials