Spring Jaxb2Marshaller Example

By Arvind Rai, March 06, 2023
On this page, we will learn Spring OXM Jaxb2Marshaller to convert XML to/from Java object.
1. Use Jaxb2Marshaller to create the instance of marshaller and unmarshaller.
2. For pretty printing using Jaxb2Marshaller, we need to set jaxb.formatted.output property as true.

Technologies Used

Find the technologies being used in our example.
1. Java
2. Gradle
3. Eclipse
4. Spring OXM

Gradle File

Find the Gradle file for Spring dependencies.
build.xml
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'concretepage'
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'
}  

JavaConfig for Jaxb2Marshaller with Pretty Print

Spring OXM provides Jaxb2Marshaller instance which is used to create instances of marshaller and unmarshaller. We can set properties in Jaxb2Marshaller for pretty printing, encoding etc. To perform pretty printing, we need to perform below steps.
map.put("jaxb.formatted.output", true);
jaxb2Marshaller.setMarshallerProperties(map); 
Find the configuration class now.
AppConfig.java
package com.concretepage;
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;
@Configuration
public class AppConfig {
	@Bean
	public Processor getHandler(){
	  Processor handler= new Processor();
	  handler.setMarshaller(getCastorMarshaller());
	  handler.setUnmarshaller(getCastorMarshaller());
	  return handler;
	}
	@Bean
	public Jaxb2Marshaller getCastorMarshaller() {
	  Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
	  jaxb2Marshaller.setPackagesToScan("com.concretepage.bean");
	  Map<String,Object> map = new HashMap<String,Object>();
	  map.put("jaxb.formatted.output", true);
	  jaxb2Marshaller.setMarshallerProperties(map);
          return jaxb2Marshaller;
	}
} 

Java Setter/Getter Class for XML Mapping

Company.java
package com.concretepage.bean;
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;
@XmlRootElement(name="company-info", namespace="com.concretepage" )
@XmlAccessorType(XmlAccessType.NONE)
public class Company {
	@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;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getCompanyName() {
		return companyName;
	}
	public void setCompanyName(String companyName) {
		this.companyName = companyName;
	}
	public String getCeoName() {
		return ceoName;
	}
	public void setCeoName(String ceoName) {
		this.ceoName = ceoName;
	}
	public Integer getNoEmp() {
		return noEmp;
	}
	public void setNoEmp(Integer noEmp) {
		this.noEmp = noEmp;
	}
} 

Create Marshaller and Unmarshaller

Now find a utility method in which we are creating Marshaller and Unmarshaller.
Processor.java
package com.concretepage;
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;
public class Processor {
    private Marshaller marshaller;
    private Unmarshaller unmarshaller;

    public void setMarshaller(Marshaller marshaller) {
        this.marshaller = marshaller;
    }

    public void setUnmarshaller(Unmarshaller unmarshaller) {
        this.unmarshaller = unmarshaller;
    }
    //Converts Object to XML file
    public void objectToXML(String fileName, Object graph) throws IOException {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fileName);
            marshaller.marshal(graph, new StreamResult(fos));
        } finally {
        	fos.close();
        }
    }
    //Converts XML to Java Object
    public Object xmlToObject(String fileName) throws IOException {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(fileName);
            return unmarshaller.unmarshal(new StreamSource(fis));
        } finally {
        	fis.close();
        }
    }
} 

Run Application

To test the application, we are creating an object of our bean and converting it into XML and then XML into Java object.
RunApplication.java
package com.concretepage;
import java.io.IOException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.concretepage.bean.Company;
public class RunApplication {
	public static void main(String[] args) throws IOException {
	   AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	   ctx.register(AppConfig.class);
	   ctx.refresh();
	   Processor processor = ctx.getBean(Processor.class);
	   //Perform Marshaling
	   Company company = new Company();
	   company.setId(100);
	   company.setCompanyName("XYZ");
	   company.setCeoName("ABCD");
	   company.setNoEmp(100);
	   processor.objectToXML("country.xml", company);
	   System.out.println("Marshaling performed");
	   //Perform UnMarshaling
	   company = (Company)processor.xmlToObject("country.xml");
	   System.out.println("After UnMarshaling Data is: id:"+ company.getId()+", CountryName:"+company.getCompanyName());
	}
} 
Output: Java object to XML.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:company-info xmlns:ns2="com.concretepage" 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.
Marshaling performed
After UnMarshaling Data is: id:100, CountryName:XYZ 

Reference

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us