StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Sunday, February 2, 2014

JAXB for XML handling

 February 02, 2014     Java     No comments   

In this article, we will explore JAXB for XML handling to read XML documents into Java objects and write Java objects into XML documents.

JAXB Introduction

Java Architecture for XML Binding (JAXB) provides a fast and convenient way to bind XML schemas and Java representations. JAXB provides methods for reading XML documents into Java objects and writing Java objects into XML documents.

JAXB annotations are used for customizing Java program elements to XML mapping. Refer to this link for list of annotations supported. http://docs.oracle.com/javaee/7/api/javax/xml/bind/annotation/package-summary.html

n this example below we use JAXB to write an XML document from Java objects and to read an XML document into Java objects

Some of the annotations we use in this example.
  1. XmlRootElement - Maps a class or an enum type to an XML element.
  2. XmlElement - Maps a JavaBean property to a XML element derived from property name.
  3. XmlAttribute - Maps a JavaBean property to a XML attribute.

First we need to create the necessary Java objects to hold our data. We create a Book object and a Catalog object to hold bunch of books. We use XmlRootElement annotation to the class and XmlAttribute annotation to the id property. Other properties are interpreted by default as XmlElement.

package com.sourcetricks.jaxb;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="book")
public class Book {

 private String id;
 private String title;
 private String author;
 private String genre;
 private String price;
 private String description;
 
 @XmlAttribute(name="id")
 public String getId() {
  return id;
 }
 public String getTitle() {
  return title;
 }
 public String getAuthor() {
  return author;
 }
 public String getGenre() {
  return genre;
 }
 public String getPrice() {
  return price;
 }
 public String getDescription() {
  return description;
 }
 public void setId(String id) {
  this.id = id;
 } 
 public void setTitle(String title) {
  this.title = title;
 }
 public void setAuthor(String author) {
  this.author = author;
 }
 public void setGenre(String genre) {
  this.genre = genre;
 }
 public void setPrice(String price) {
  this.price = price;
 }
 public void setDescription(String description) {
  this.description = description;
 }
}
Next we create a catalog object that holds a list of books.
package com.sourcetricks.jaxb;

import java.util.ArrayList;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="catalog")
public class Catalog {

 @XmlElement(name="book")
 private ArrayList<Book> listOfBooks;
 
 public Catalog() {
  listOfBooks = new ArrayList<Book>();
 }
 
 public void addBook(Book book) {
  listOfBooks.add(book);
 }
 
 public void printBooks() {
  for ( Book b : listOfBooks ) {
   System.out.println(b.getId());
   System.out.println(b.getTitle());
   System.out.println(b.getAuthor());
   System.out.println(b.getGenre());
   System.out.println(b.getPrice());
  }
 }
}

Program to marshal and unmarshal the XML documents

Finally the test program which marshals and unmarshals the XML documents.
package com.sourcetricks.jaxb;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class JaxbTest {

 private void marshalTest() {
  // Create a catalog
  Catalog catalog = new Catalog();

  // Add some books
  Book book1 = new Book();
  book1.setId("100");
  book1.setTitle("XML Developer's Guide");
  book1.setAuthor("Gambardella, Matthew");
  book1.setGenre("Computer");
  book1.setPrice("44.95");
  book1.setDescription("An in-depth look at creating applications with XML");
  catalog.addBook(book1);

  // Marshal the catalog object into XML
  try {
   JAXBContext context = JAXBContext.newInstance(Catalog.class);
   Marshaller marshaller = context.createMarshaller();
   // Format the output
   marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
   System.out.println("------------- Marshal Test----------------------");
   marshaller.marshal(catalog, System.out);   
  } catch (JAXBException e) {
   e.printStackTrace();
  }
 }
 
 public void unmarshalTest() {
  FileReader reader = null;
  // Read an XML document and unmarshal into Java objects
  try {
   reader = new FileReader("resources/input.xml");  
   JAXBContext context = JAXBContext.newInstance(Catalog.class);
   Unmarshaller unmarshaller = context.createUnmarshaller();
   Catalog c = (Catalog) unmarshaller.unmarshal(reader);
   System.out.println("------------- Unmarshal Test----------------------");
   c.printBooks();
  } 
  catch ( FileNotFoundException e ) {
   e.printStackTrace();
  } 
  catch (JAXBException e) {
   e.printStackTrace();
  } 
  finally {
   if ( reader != null )
    try {
     reader.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
  }
 }

 public static void main(String[] args) {
  JaxbTest j = new JaxbTest();
  j.marshalTest();
  j.unmarshalTest();  
 }
}
Output
------------- Marshal Test----------------------
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<catalog>
    <book id="100">
        <author>Gambardella, Matthew</author>
        <description>An in-depth look at creating applications with XML</description>
        <genre>Computer</genre>
        <price>44.95</price>
        <title>XML Developer's Guide</title>
    </book>
</catalog>
------------- Unmarshal Test----------------------
bk101
XML Developer's Guide
Gambardella, Matthew
Computer
44.95
  • Share This:  
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Implement caching in a Spring Boot microservice using Redis
    In this article we will explore how to use Redis as a data cache for a Spring Boot microservice using PostgreSQL as the database. Idea is to...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Spring Boot with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Getting started with Kafka in Python
    This article will provide an overview of Kafka and how to get started with Kafka in Python with a simple example. What is Kafka? ...
  • Getting started in GraphQL with Spring Boot
    In this article we will explore basic concepts on GraphQL and look at how to develop a microservice in Spring Boot with GraphQL support. ...

Copyright © StackStalk