Introduction:
@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
- JAXB stands for Java Architecture for XML Binding.
- Jaxb provides convert the object into XML and XML into the object.
Marshaling
Steps to convert the object into XML
1. Create a POJO class.
2. Create a JAXB context object.
3. Create the marshaller object.
4. Create the content tree by using set methods.
5. Call the marshaller method.
Here is the Sample Snippet of java 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; } }
@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.FileNotFoundException; import java.io.FileOutputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; /** * * @author Janardhan Randhi */ public class ObjectToXml { public static void main(String[] args) throws JAXBException, FileNotFoundException { JAXBContext contextObj = JAXBContext.newInstance(Obj2Xml.class); Marshaller marshallerObj = contextObj.createMarshaller(); marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Obj2Xml obj = new Obj2Xml(1, "Ramjanardhan","Randhi", 50000); marshallerObj.marshal(obj, new FileOutputStream("JavaSnippets.xml")); } }