Introduction:
- JAXB stands for Java Architecture for XML Binding.
- Jaxb provides convert the object into XML and XML into the object.
Unmarshalling
- Unmarshalling means convert the XML into the object.
Steps to convert XML into the object
1. Create a POJO class.
2. Create a JAXB context object.
3. Create the unmarshalled object.
5. Call the unmarshaller method.
6. Use the getter methods to get the data.
Here is the POJO class
package com.JavaAnippets; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * * @author Janardhan Randhi */ @XmlRootElement public class Obj2Xml { private int id; private String FirstName; private String LastName; private float salary; public Obj2Xml() {} public Obj2Xml(int id, String FirstName, String LastName, float salary) { super(); this.id = id; this.FirstName = FirstName; this.LastName = LastName; this.salary = salary; } @XmlAttribute public int getId() { return id; } public void setId(int id) { this.id = id; } @XmlElement public String getFirstName() { return FirstName; } public void setFirstName(String FirstName) { this.FirstName = FirstName; } @XmlElement public String getLastName() { return LastName; } public void setLastName(String LastName) { this.LastName = LastName; } @XmlElement public float getSalary() { return salary; } public void setSalary(float salary) { this.salary = salary; } }
@XmlRootElement specifies the root element of the XML document.
@XmlAttribute specifies the attribute of the root element.
@XmlElement specifies the sub-element of the root element.
Here is the Main class
Output:
@XmlAttribute specifies the attribute of the root element.
@XmlElement specifies the sub-element of the root element.
Here is the Main class
package com.JavaAnippets; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; /** * * @author Janardhan Randhi */ public class Xml2Object { public static void main(String[] args) throws JAXBException { File file = new File("JavaSnippets.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Obj2Xml.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Obj2Xml obj = (Obj2Xml) jaxbUnmarshaller.unmarshal(file); System.out.println(obj.getId() + " " + obj.getFirstName() + " " + obj.getLastName() +" " + obj.getSalary()); } }