The term JAXB stands for Java Architecture for XML Binding. Java programmers may use it to translate Java classes to XML representations. Java objects may be marshaled into XML and vice versa using JAXB. Sun provides an OXM (Object XML Mapping) or O/M framework.
Note: The biggest and only advantage of JAXB is as there’s no need to develop callback methods or create a SAX or DOM parser.
Implementation: Spring and JAXB Integration (Marshalling Java Object into XML)
The project Structure will look as follows:
We build Marshaller and Unmarshaller instances using the Jaxb2Marshaller instance. In Jaxb2Marshaller, set the jaxb.formatted.output attribute to true for nice printing. To map XML tags and attributes to Java objects, we need to construct a Java bean with properties that are mapped to XML tags and attributes. Using javax.xml.bind, annotate properties. XmlAttribute and XmlElement, for example, are annotations that link XML attributes and elements to Java bean properties.
Remember: To run the application, we need the following software as listed:
- Java 7
- Gradle
- Eclipse
- Spring-Oxm:4.1.5.RELEASE
Gradle File for Spring OXM and Spring Boot Starter
Step 1: Find the Gradle file for spring OXM and spring Boot Starter.
File: build.xml
XML
apply plugin: 'java' apply plugin: 'eclipse' archivesBaseName = 'neveropen' version = '1' repositories { mavenCentral() } dependencies { compile 'org.springframework.boot:spring-boot-starter:1.2.2.RELEASE' compile 'org.springframework:spring-oxm:4.1.5.RELEASE' } |
Annotation Based Configuration File for Jaxb2Marshaller and Pretty Print
The Jaxb2Marshaller instance in Spring OXM is used to construct Marshaller and Unmarshaller instances.
Step 2: In Jaxb2Marshaller, we may configure settings for nice XML printing, encoding, and so on. To create a beautiful print, follow the instructions below.
map.put("jaxb.formatted.output", true); jaxb2Marshaller.setMarshallerProperties(map);
File: AppConfig.java
Java
// Java Program to Illustrate Configuration Class package com.neveropen; // Importing required classes import java.util.HashMap; import java.util.Map; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.oxm.jaxb.Jaxb2Marshaller; // Annotation @Configuration // Class public class AppConfig { // Method @Bean public Processor getHandler() { Processor handler = new Processor(); handler.setMarshaller(getCastorMarshaller()); handler.setUnmarshaller(getCastorMarshaller()); return handler; } // Method @Bean public Jaxb2Marshaller getCastorMarshaller() { Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller(); jaxb2Marshaller.setPackagesToScan( "com.neveropen.bean" ); Map<String, Object> map = new HashMap<String, Object>(); map.put( "jaxb.formatted.output" , true ); jaxb2Marshaller.setMarshallerProperties(map); return jaxb2Marshaller; } } |
Java supports many annotations for XML and Java object mapping, including @XmlRootElement, @XmlAccessorType, @XmlAttribute, and @XmlElement.
Step 3: Use @XmlAttribute to acquire java properties as XML attributes, and @XmlElement annotation on properties to retrieve XML subtags.
File: Company.java
Java
// Java Program to Illustrate Bean for XML Mapping package com.neveropen.bean; // Importing required classes import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; // Annotation @XmlRootElement (name = "company-info" , namespace = "com.neveropen" ) @XmlAccessorType (XmlAccessType.NONE) // Class public class Company { // Class data members @XmlAttribute (name = "id" ) private Integer id; @XmlElement (name = "company-name" ) private String companyName; @XmlElement (name = "ceo-name" ) private String ceoName; @XmlElement (name = "no-emp" ) private Integer noEmp; // Getters and setters public Integer getId() { return id; } public void setId(Integer id) { // this keyword refers to current itself this .id = id; } // Getter and Setter public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this .companyName = companyName; } // Getter and Setter public String getCeoName() { return ceoName; } public void setCeoName(String ceoName) { this .ceoName = ceoName; } // Getter and Setter public Integer getNoEmp() { return noEmp; } public void setNoEmp(Integer noEmp) { this .noEmp = noEmp; } } |
Define Method for Marshaller and Unmarshaller
Step 4: Find a utility method in which we are calling Marshaller and Unmarshaller.
File: Processor.java
Java
// Java Program Defining Method for // Marshaller and Unmarshaller package com.neveropen; // Importing required classes import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.springframework.oxm.Marshaller; import org.springframework.oxm.Unmarshaller; // Class public class Processor { // Class data members private Marshaller marshaller; private Unmarshaller unmarshaller; // Setter public void setMarshaller(Marshaller marshaller) { this .marshaller = marshaller; } public void setUnmarshaller(Unmarshaller unmarshaller) { this .unmarshaller = unmarshaller; } // Converting Object to XML file public void objectToXML(String fileName, Object graph) throws IOException { FileOutputStream fos = null ; // Try block to check for exceptions try { fos = new FileOutputStream(fileName); marshaller.marshal(graph, new StreamResult(fos)); } // finally block that will execute for sure finally { // Closing the connections fos.close(); } } // Method // To Convert XML to Java Object public Object xmlToObject(String fileName) throws IOException { FileInputStream fis = null ; // Try block to check for exceptions try { fis = new FileInputStream(fileName); return unmarshaller.unmarshal( new StreamSource(fis)); } // finally block that will execute for sure finally { // Closing the connections fis.close(); } } } |
Step 5: Run the application
Now in order to test the program, we can create a bean object, convert it to XML, and then transform that XML back to a Java object.
File: RunApplication.java
Java
// Java Program to Illustrate Application Class package com.neveropen; // Importing required classes import com.neveropen.bean.Company; import java.io.IOException; import org.springframework.beans.BeansException; import org.springframework.context.annotation.AnnotationConfigApplicationContext; // Application/Main Class public class RunApplication { // Main driver method public static void main(String[] args) throws IOException { // Try block to check for exceptions try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) { ctx.register(AppConfig. class ); ctx.refresh(); Processor processor = ctx.getBean(Processor. class ); // Perform Marshalling Company company = new Company(); company.setId( 1000 ); company.setCompanyName( "XYZ" ); company.setCeoName( "ABCD" ); company.setNoEmp( 100 ); processor.objectToXML( "country.xml" , company); // Display message only System.out.println( "Marshalling performed" ); // Perform UnMarshalling company = (Company)processor.xmlToObject( "country.xml" ); // Display message only System.out.println( "After UnMarshalling Data is: id:" + company.getId() + ", CountryName:" + company.getCompanyName()); } // Catch block to handle exceptions catch (BeansException | IllegalStateException e) { // Display exceptions along with line number // using printStackTrace() method e.printStackTrace(); } } } |
Output: java object to XML is as follows:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ns2:company-info xmlns:ns2="com.neveropen" id="100"> <company-name>XYZ</company-name> <ceo-name>ABCD</ceo-name> <no-emp>100</no-emp> </ns2:company-info>
Output: XML to java object is as follows: