Sunday 1 March 2015

JAXB : XML Read & Write in Java

JAXB is "Java Architecture for xml binding" and consists in:
-Schema compiler
-Schema generator
-Binding runtime framework

The classes to read, write and binding XML in Java are included in JavaSE and JavaEE. These classes are contained in package: javax.xml.bind.*

We will analyze two examples of read and write XML using marshalling and unmarshalling as in the following diagram:


Read/Write operations:

XML --> Unmarshalling --> Object
XML <-- Marshalling    <--  Object

By default the encoding in the marshalling process is UTF-8

Example:
In the following example the readXML method will read an XML file and it will be converted into an Object. Then the writeXML method transform the object into XML again.

XML menu

Object menu
Not to forget to use annotations to indicate the root and elements: @XmlRootElement and @XmlElement :



  • Read XML with JAXB
The steps are:
-Create a JAXBContext
-Create object Unmarshaller
-Define inputStream object
-Read XML using the unmarshalling object



  • Write XML with JAXB 
The steps are:
-Create a JAXBContext
-Create object Marshaller
-Define the output format
-Define outputStream object
-Write XML using the marshalling object



  • Executing the main method - Results


The output in console will be:
cheeseburguer
coke
chips
salad

Also as a result of writing method a new output.xml file will be created:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<menu>
    <drink>coke</drink>
    <side>chips</side>
    <side>salad</side>
    <type>cheeseburguer</type>
</menu>


No comments:

Post a Comment