Friday 25 September 2015

JAXB


jaxb
stands for Java Architecture for XML Binding. It provides mechanism to marshal (write) java objects into XML and unmarshal (read) XML into object. Simply, you can say it is used to convert java object into xml and vice-versa.




@XmlRootElement specifies the root element for the xml document.

@XmlAttribute specifies the attribute for the root element.


@XmlElement specifies the sub element for the root element.

Java pojo:

import javax.xml.bind.annotation.XmlAttribute;  
import javax.xml.bind.annotation.XmlElement;  
import javax.xml.bind.annotation.XmlRootElement;  
  
@XmlRootElement  
public class Profile{  
    private int id;  
    private String name;  
  
public Profile() {}  
public Profile(int id, String name) {  
    super();  
    this.id = id;  
    this.name = name;  
}  
@XmlAttribute  
public int getId() {  
    return id;  
}  
public void setId(int id) {  
    this.id = id;  
}  
@XmlElement  
public String getName() {  
    return name;  
}  
public void setName(String name) {  
    this.name = name;  
}    

}  


ObjectToXml.java::


import java.io.FileOutputStream;  
  
import javax.xml.bind.JAXBContext;  
import javax.xml.bind.Marshaller;  
  
  
public class ObjectToXml {  
public static void main(String[] args) throws Exception{  
    JAXBContext contextObj = JAXBContext.newInstance(Profile.class);  
  
    Marshaller marshallerObj = contextObj.createMarshaller();  
    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  
  
    Profile p1=new Profile(1,"Vimal Jaiswal");  
      
    marshallerObj.marshal(p1, new FileOutputStream("profile.xml"));  
       
}  
}  


xml to object::

import java.io.File;  
import javax.xml.bind.JAXBContext;  
import javax.xml.bind.JAXBException;  
import javax.xml.bind.Unmarshaller;  
  
public class XMLToObject {  
public static void main(String[] args) {  
     try {    
            File file = new File("profile.xml");    
            JAXBContext jaxbContext = JAXBContext.newInstance(Profile.class);    
         
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();    
            Profile p=(Profile) jaxbUnmarshaller.unmarshal(file);    
            System.out.println(p.getId()+" "+p.getName());  
              
          } catch (JAXBException e) {e.printStackTrace(); }    
         
}  

}  




No comments:

Post a Comment