JAXB -Play With XML

JAXB  -Play With XML
   (A Simple Example With Explanation)
      
    
        JAXB stands for Java Architecture For XML binding.Using this we can Write and Read An XML File .Unlike SAX,DOM no need to have much knowledge on xml parsing .
JAXB is  a very easy technique to understand

  1. Writing an XML file is called as marshaling
  2. Reading an XML file is called as unmarshaling





        Let us see the step by step procedure to perform marshaling & un marshaling.

         Marshaling 

As Mentioned above marshaling means writing xml file form java object.
The first step is creating  java class from a schema.if we have a schema file required we can create pojo classess from it using xsd jar.xsd jar is available with java by default.xsd is a binding compiler which is mentioned in the diagram.
  1. create a java project in eclispe IDE
  2. create a new xsd file inside the project.  Right click on the project new - Xml schema

 

 


3. Then copy the below content inside the xsd file created,save the file

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xs:element name="employee" type="employee"/>

  <xs:complexType name="employee">
    <xs:sequence>
      <xs:element name="name" type="xs:string" minOccurs="0"/>
      <xs:element name="salary" type="xs:double"/>
      <xs:element name="designation" type="xs:string" minOccurs="0"/>
      <xs:element name="address" type="address" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="xs:int" use="required"/>
  </xs:complexType>

  <xs:complexType name="address">
    <xs:sequence>
      <xs:element name="city" type="xs:string" minOccurs="0"/>
      <xs:element name="line1" type="xs:string" minOccurs="0"/>
      <xs:element name="line2" type="xs:string" minOccurs="0"/>
      <xs:element name="state" type="xs:string" minOccurs="0"/>
      <xs:element name="zipcode" type="xs:long"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>


4.Inside the source folder create a package like com.jaxb.demo

 5.open a command window in the location where you created  a project
  Type following command

    Command : xjc -d src -p com.jaxb.demo employee.xsd
 Here com.jaxb.demo is the package name where you are going to save your java classes and employee.xsd is your schema file which we created already.

  You can see the above details in the command window once you executed the command given 
6.Now go to your project in eclipse and check the package we created.
inside the package you ll have your java classes now




With your java classes you will get class called ObjectFactory.java.Will explain the purpose of this little later..so now we can perform marshaling  create a java class in the same package with the name marshalSample.java


marshalSample.java
package com.jaxb.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import javax.xml.bind.JAXB;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;


public class marshalSample {
      public static void main(String[] args) throws FileNotFoundException {
         
           
            Employee emp = new Employee();
          // setting values to each variable in the employee class
            emp.setId(147);
            emp.setName("Saradha M");
            emp.setSalary(23000);
            emp.setDesignation("AssociateSoftwareEngineer");
            Address ad=new Address();
            ad.setLine1("Johnson street");
            ad.setLine2("Near airport");
            ad.setCity("Los Angels");
            ad.setState("California");
            ad.setZipcode(6410068938);
            emp.setAddress(ad);
       
           
       
            // create an element for marshalling
            JAXBElement<Employee> Employee = (new ObjectFactory()).createEmployee(emp);
       
            // create a Marshaller and marshal to System.out
            JAXB.marshal(Employee, new FileOutputStream(new File("E:\\My Workspace\\JAXBTutorial\\target\\Employee.xml")));
          }
        }
This will create the xml file for the given java object in the target folder


   

  UnMarshaling

 unmarshaling means reading the xml file.we are going to read a xml file which we created inside the target folder.
create a java class inside the package ,and copy the bellow code .

unmarshalSample.java
package com.jaxb.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

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


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

            JAXBContext jaxbContext = JAXBContext
                    .newInstance("com.example.jaxb");
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            JAXBElement<?> emp = (JAXBElement<?>) unmarshaller
                    .unmarshal(new FileInputStream("E:\\Employee.xml"));
            Employee emp1 = (Employee) emp.getValue();

            System.out.println("emp Name: " + emp1.getName());
            System.out.println("emp Id: " + emp1.getId());
            System.out.println("emp designation: " + emp1.getDesignation());
            System.out.println("emp salary: " + emp1.getSalary());
            System.out.println("emp address: " + emp1.getAddress().getLine1()+","+emp1.getAddress().getLine2()+","+emp1.getAddress().getCity()+","+emp1.getAddress().getState()+","+emp1.getAddress().getZipcode());

        } catch (JAXBException je) {
          je.printStackTrace();
        } catch (IOException ioe) {
          ioe.printStackTrace();
        }
      }
        }
The above program reads the xml content and displays the values of each java object  .Here we can know the purpose of ObjectFactory class .
 JAXBContext jaxbContext = JAXBContext
                .newInstance("com.example.jaxb");

 
If ObjectFactory .java class is not there You get that exception when you use the JAXBContext.newInstance(String) factory method, where you pass in the package name as the argument. This does require the ObjectFactory to be there, otherwise, JAXB doesn't know which classes to process.

If you don't have an ObjectFactory, you need to JAXBContext.newInstance(Class...) instead, passing in the explicit list of annotated classes to add to the context.
 

    
output:
emp Name: Saradha M
emp Id: 147
emp designation: AssociateSoftwareEngineer
emp salary: 23000.0
emp address:
Johnson street,Near airport,Los Angels,California,6410068938
 






Comments

  1. Nice Article...... Thanks for the post..

    ReplyDelete
  2. Need technical help from tech geeks. come here.

    chat.oneindia.in:443
    chat.parachat.com

    Meet the experts and get the lifetime solutions at free of cost.Also contribute the doubts to young generation..

    ReplyDelete

Post a Comment

Popular posts from this blog

Get rid of boring for loop and try using "range" and "rangeClosed"

Custom Exception Handling For Spring Boot Rest Controller

HOW TO USE NOTE PAD AS YOUR PERSONAL DAIRY!!!!!