A Technology Blog About Code Development, Architecture, Operating System, Hardware, Tips and Tutorials for Developers.

Thursday, November 15, 2012

XML Parsing in java - JAXB

12:11:00 AM Posted by Satish , No comments
JAXB, stands for Java Architecture for XML Binding, using JAXB annotation to convert Java object to / from XML file. In this tutorial, we show you how to use JAXB to do following stuffs :

 JAVA AND XML
                   XML Parsing using Java
                         1. DOM XML Parser
                         2. SAX XML Parser
                         3. StaX XML Parser
                         4. JAXB XML Parser
  • Marshalling – Convert a Java object into a XML file.
  • Unmarshalling – Convert XML content into a Java Object.
Working with JAXB is easy, just annotate object with JAXB annotation, later use jaxbMarshaller.marshal() or jaxbMarshaller.unmarshal() to do the object / XML conversion. No extra jaxb libraries are required if you are using JDK1.6 or above, because JAXB is bundled in JDK 1.6. 

I have used the following things for this tutorial.

1. JDK 7
2. Maven2

Let's create a java project using maven 

1
mvn archetype:generate -DgroupId=com.techiekernel -DartifactId=ParserDemo -Dpackagename=com.techiekernel

Now create a sample xml document to parse

 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
<?xml version="1.0" encoding="UTF-8"?>
<products>
 <product>
  <name>R15</name>
  <make>Yamaha</make>
  <engine-cc>150</engine-cc>
  <type>sports</type>
 </product>
 <product>
  <name>Duke</name>
  <make>KTM</make>
  <engine-cc>200</engine-cc>
  <type>Street</type>
 </product>
 <product>
  <name>GS650GS Sertao</name>
  <make>BMW</make>
  <engine-cc>650</engine-cc>
  <type>Enduro</type>
 </product>
 <product>
  <name>Multistada</name>
  <make>Ducati</make>
  <engine-cc>1210</engine-cc>
  <type>Touring</type>
 </product>
</products>

Now let's create a classes too hold the data. So we have to create one class called Product and one called Products which will keep the list of product.

Product.java
 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
package com.techiekernel.parser.jaxb;

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

@XmlRootElement
public class Product {
 String name;
 String make;
 String engine;
 String type;
 
 public String getName() {
  return name;
 }
 
 @XmlElement
 public void setName(String name) {
  this.name = name;
 }
 
 public String getMake() {
  return make;
 }
 
 @XmlElement
 public void setMake(String make) {
  this.make = make;
 }
 
 public String getEngine() {
  return engine;
 }
 
 @XmlElement(name="engine-cc")
 public void setEngine(String engine) {
  this.engine = engine;
 }
 
 public String getType() {
  return type;
 }
 
 @XmlElement
 public void setType(String type) {
  this.type = type;
 }

 @Override
 public String toString() {
  return "Product [name=" + name + ", make=" + make + ", engine="
    + engine + ", type=" + type + ", toString()="
    + super.toString() + "]";
 }
}

Products.java
 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
package com.techiekernel.parser.jaxb;

import java.util.List;

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

@XmlRootElement
public class Products {
 List<Product> products;

 public List<Product> getProducts() {
  return products;
 }

 @XmlElement(name="product")
 public void setProducts(List<Product> products) {
  this.products = products;
 }

 @Override
 public String toString() {
  return "Products [products=" + products + ", toString()="
    + super.toString() + "]";
 }
 
 
}

Now time to write a demo program which will parse the XML and populate the data in object.

 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
package com.techiekernel.parser.jaxb;

import java.io.File;

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

public class JaxbReader {
 public static void main(String[] args) {

  try {
   File file = new File("product.xml");
   JAXBContext jaxbContext = JAXBContext.newInstance(Products.class);

   Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
   Products products = (Products) jaxbUnmarshaller.unmarshal(file);
   System.out.println(products.getProducts());

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

 }
}

Output:

1
[Product [name=R15, make=Yamaha, engine=150, type=sports, toString()=com.techiekernel.parser.jaxb.Product@41cd79], Product [name=Duke, make=KTM, engine=200, type=Street, toString()=com.techiekernel.parser.jaxb.Product@18e905], Product [name=GS650GS Sertao, make=BMW, engine=650, type=Enduro, toString()=com.techiekernel.parser.jaxb.Product@16a5acd], Product [name=Multistada, make=Ducati, engine=1210, type=Touring, toString()=com.techiekernel.parser.jaxb.Product@16f6006]]

Let's also write a code which will parse the object to xml.

 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
package com.techiekernel.parser.jaxb;

import java.util.ArrayList;
import java.util.List;

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

public class JaxbWriter {
 public static void main(String[] args) {

  Products products = new Products();

  List<Product> productList = new ArrayList<Product>();
  Product product = new Product();
  product.setName("R1");
  product.setMake("Yamaha");
  product.setEngine("1000");
  product.setType("sports");

  productList.add(product);

  product = new Product();
  product.setName("GS1200R");
  product.setMake("BMW");
  product.setEngine("1200");
  product.setType("Enduro");

  productList.add(product);
  
  products.setProducts(productList);

  try {

   JAXBContext jaxbContext = JAXBContext.newInstance(Products.class);
   Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

   jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

   jaxbMarshaller.marshal(products, System.out);

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

 }
}

Output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<products>
    <product>
        <engine-cc>1000</engine-cc>
        <make>Yamaha</make>
        <name>R1</name>
        <type>sports</type>
    </product>
    <product>
        <engine-cc>1200</engine-cc>
        <make>BMW</make>
        <name>GS1200R</name>
        <type>Enduro</type>
    </product>
</products>

Source Code:


You can pull the code from GitHub.

0 comments:

Post a Comment