HOME

The previous tutorials have explained the conversion of Java Objects to JSON payload and vice versa, i.e. conversion of JSON payload to Java Objects using Jackson API.

This tutorial explains parsing the XML document to Java objects using Jackson API.

To parse the above XML, we will use the Jackson library. Use the latest Jackson library.

 <dependency>     <groupId>com.fasterxml.jackson.dataformat</groupId>     <artifactId>jackson-dataformat-xml</artifactId>     <version>2.13.0</version> </dependency> 

We are going to parse the following XML.

 <Employee>   <firstName>Vibha</firstName>   <lastName>Singh</lastName>   <age>30</age>   <salary>75000.0</salary>   <designation>Manager</designation>   <contactNumber>+919999988822</contactNumber>   <emailId>abc@test.com</emailId>   <gender>female</gender>   <maritalStatus>married</maritalStatus> </Employee> 

We will create an XML from POJO and vice versa now, which is generally called serialization and deserialization using Jackson APIs.

XmlMapper is a subclass of ObjectMapper which is used in JSON serialization. However, it adds some XML-specific tweaks to the parent class.

 XmlMapper xmlMapper = new XmlMapper(); 

We can now look at how to use it to do the actual serialization. Let's create a Java class first:

Below is the sample code of the Employee table, which contains the data members needed for Employee XML and their corresponding getter and setter methods.

 public class Employee {  	// Data members of POJO class 	private String firstName; 	private String lastName; 	private int age; 	private double salary; 	private String designation; 	private String contactNumber; 	private String emailId; 	private String gender; 	private String maritalStatus;  	// Getter and setter methods 	public String getFirstName() { 		return firstName; 	}  	public void setFirstName(String firstName) { 		this.firstName = firstName; 	}  	public String getLastName() { 		return lastName; 	}  	public void setLastName(String lastName) { 		this.lastName = lastName; 	}  	public int getAge() { 		return age; 	}  	public void setAge(int age) { 		this.age = age; 	}  	public double getSalary() { 		return salary; 	}  	public void setSalary(double salary) { 		this.salary = salary; 	}  	public String getDesignation() { 		return designation; 	}  	public void setDesignation(String designation) { 		this.designation = designation; 	}  	public String getContactNumber() { 		return contactNumber; 	}  	public void setContactNumber(String contactNumber) { 		this.contactNumber = contactNumber; 	}  	public String getEmailId() { 		return emailId; 	}  	public void setEmailId(String emailId) { 		this.emailId = emailId; 	}  	public String getGender() { 		return gender; 	}  	public void setGender(String gender) { 		this.gender = gender; 	}  	public String getMaritalStatus() { 		return maritalStatus; 	}  	public void setMaritalStatus(String maritalStatus) { 		this.maritalStatus = maritalStatus; 	}  } 

Writing XML is done using the various writeValue() methods that Jackson exposes.

   public class EmployeeXMLTest {  	@Test 	public void serializationTest() {  		// Create an object of POJO class 		Employee employee = new Employee(); 	 		employee.setFirstName("Vibha"); 		employee.setLastName("Singh"); 		employee.setAge(30); 		employee.setSalary(75000); 		employee.setDesignation("Manager"); 		employee.setContactNumber("+919999988822"); 		employee.setEmailId("abc@test.com"); 		employee.setMaritalStatus("married"); 		employee.setGender("female");  		// Converting a Java class object to XML 		XmlMapper xmlMapper = new XmlMapper();  		try { 			String employeeXml = xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee); 			System.out.println(employeeXml); 		} catch (JsonProcessingException e) { 			e.printStackTrace(); 		}  	} } 

Output

Nested Elements in XML

Let us create a complex XML now as shown below.

 <Employees>   <name>     <firtsname>John</firtsname>     <middlename>Dave</middlename>     <lastname>William</lastname>   </name>   <contactdetails>     <deskNumber>00-428507</deskNumber>     <mobileNumber>+917823561231</mobileNumber>     <emergencyDetails>       <emergency_no1>+91 1212898920</emergency_no1>       <emergency_no2>+91 9997722123</emergency_no2>       <emergency_no3>+91 8023881245</emergency_no3>     </emergencyDetails>   </contactdetails>   <age>30</age>   <salary>75000.0</salary>   <designation>Manager</designation>   <emailId>abc@test.com</emailId>   <gender>female</gender>   <maritalStatus>married</maritalStatus> </Employees> 

Here, In this new structure, we have introduced a nested name element as well as contactdetails element which is further nested to emergencyDetails elements. With our current code, we cannot extract or create the new nested section. So, along with creating a POJO class for Employees, will create a POJO class for name, contactDetails, and emergencyDetails.

Employees

 public class Employees {  	Name name; 	ContactDetails contactdetails;  	private int age; 	private double salary; 	private String designation; 	private String emailId; 	private String gender; 	private String maritalStatus;  	// Getter and setter methods 	public Name getName() { 		return name; 	}  	public void setName(Name name) { 		this.name = name; 	}  	public ContactDetails getContactdetails() { 		return contactdetails; 	}  	public void setContactdetails(ContactDetails contactdetails) { 		this.contactdetails = contactdetails; 	}  	public int getAge() { 		return age; 	}  	public void setAge(int age) { 		this.age = age; 	}  	public double getSalary() { 		return salary; 	}  	public void setSalary(double salary) { 		this.salary = salary; 	}  	public String getDesignation() { 		return designation; 	}  	public void setDesignation(String designation) { 		this.designation = designation; 	}  	public String getEmailId() { 		return emailId; 	}  	public void setEmailId(String emailId) { 		this.emailId = emailId; 	}  	public String getGender() { 		return gender; 	}  	public void setGender(String gender) { 		this.gender = gender; 	}  	public String getMaritalStatus() { 		return maritalStatus; 	}  	public void setMaritalStatus(String maritalStatus) { 		this.maritalStatus = maritalStatus; 	}  } 

Name

 public class Name {  	private String firtsname; 	private String middlename; 	private String lastname;  	public String getFirtsname() { 		return firtsname; 	}  	public void setFirtsname(String firtsname) { 		this.firtsname = firtsname; 	}  	public String getMiddlename() { 		return middlename; 	}  	public void setMiddlename(String middlename) { 		this.middlename = middlename; 	}  	public String getLastname() { 		return lastname; 	}  	public void setLastname(String lastname) { 		this.lastname = lastname; 	}  } 

ContactDetails -As you can see that EmergencyDetails element which contains emergency_no1, emergency_no2, and emergency_no3 are nested within ContactDetails, so we have created a separate POJO class for EmergencyDetails.

 public class ContactDetails {  	private String deskNumber; 	private String mobileNumber;  	EmergencyDetails emergencyDetails;  	public EmergencyDetails getEmergencyDetails() { 		return emergencyDetails; 	}  	public void setEmergencyDetails(EmergencyDetails emergencyDetails) { 		this.emergencyDetails = emergencyDetails; 	}  	public String getDeskNumber() { 		return deskNumber; 	}  	public void setDeskNumber(String deskNumber) { 		this.deskNumber = deskNumber; 	}  	public String getMobileNumber() { 		return mobileNumber; 	}  	public void setMobileNumber(String mobileNumber) { 		this.mobileNumber = mobileNumber; 	}  } 

EmergencyDetails

 public class EmergencyDetails {  	private String emergency_no1; 	private String emergency_no2; 	private String emergency_no3;  	public String getEmergency_no1() { 		return emergency_no1; 	}  	public void setEmergency_no1(String emergency_no1) { 		this.emergency_no1 = emergency_no1; 	}  	public String getEmergency_no2() { 		return emergency_no2; 	}  	public void setEmergency_no2(String emergency_no2) { 		this.emergency_no2 = emergency_no2; 	}  	public String getEmergency_no3() { 		return emergency_no3; 	}  	public void setEmergency_no3(String emergency_no3) { 		this.emergency_no3 = emergency_no3; 	}  } 

Next, we create our serializeToXML() method:

 public class XmlSerializationDemo {  	@Test 	public void serializationXML() throws JsonProcessingException {  		Employees employee = new Employees();  		Name empname = new Name(); 		empname.setFirtsname("John"); 		empname.setMiddlename("Dave"); 		empname.setLastname("William");  		employee.setName(empname); 		employee.setAge(30); 		employee.setSalary(75000); 		employee.setDesignation("Manager");  		ContactDetails contdetails = new ContactDetails(); 		contdetails.setDeskNumber("00-428507"); 		contdetails.setMobileNumber("+917823561231");  		EmergencyDetails emergency = new EmergencyDetails(); 		emergency.setEmergency_no1("+91 1212898920"); 		emergency.setEmergency_no2("+91 9997722123"); 		emergency.setEmergency_no3("+91 8023881245"); 		contdetails.setEmergencyDetails(emergency);  		employee.setContactdetails(contdetails);  		employee.setEmailId("abc@test.com"); 		employee.setMaritalStatus("married"); 		employee.setGender("female");  		XmlMapper xmlMapper = new XmlMapper();  		try { 			String employeeXml = xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee); 			System.out.println(employeeXml); 		} catch (JsonProcessingException e) { 			e.printStackTrace(); 		}        //To save the XML in a file and place under the project 		String userDir = System.getProperty("user.dir"); 		try { 			xmlMapper.writerWithDefaultPrettyPrinter() 					.writeValue(new File(userDir + "\\src\\test\\resources\\NestedXMLExample.xml"), employee); 		} catch (StreamWriteException e) { 			e.printStackTrace(); 		} catch (DatabindException e) { 			e.printStackTrace(); 		} catch (IOException e) { 			e.printStackTrace(); 		} 	} } 

Output

The file is saved under src/test/resources as NestedXMLExample.

There is another way to do the same job of converting Java Object to a complex XML, but which looks more sophisticated and less a number of lines of code.

I'll use the same complex XML structure.

In this method, we will create a default constructor as well as a parametrized Constructor to pass the arguments for each POJO Class.

Employee

 public class Employees {  	Name name; 	ContactDetails contactdetails;  	private int age; 	private double salary; 	private String designation; 	private String emailId; 	private String gender; 	private String maritalStatus;  	public Employees() { 		super(); 	}  	public Employees(Name name, ContactDetails contactdetails, int age, double salary, String designation, 			String emailId, String gender, String maritalStatus) {  		this.name = name; 		this.contactdetails = contactdetails; 		this.age = age; 		this.salary = salary; 		this.designation = designation; 		this.emailId = emailId; 		this.gender = gender; 		this.maritalStatus = maritalStatus; 	}  	// Getter and setter methods 	public Name getName() { 		return name; 	}  	public void setName(Name name) { 		this.name = name; 	}  	public ContactDetails getContactdetails() { 		return contactdetails; 	}  	public void setContactdetails(ContactDetails contactdetails) { 		this.contactdetails = contactdetails; 	}  	public int getAge() { 		return age; 	}  	public void setAge(int age) { 		this.age = age; 	}  	public double getSalary() { 		return salary; 	}  	public void setSalary(double salary) { 		this.salary = salary; 	}  	public String getDesignation() { 		return designation; 	}  	public void setDesignation(String designation) { 		this.designation = designation; 	}  	public String getEmailId() { 		return emailId; 	}  	public void setEmailId(String emailId) { 		this.emailId = emailId; 	}  	public String getGender() { 		return gender; 	}  	public void setGender(String gender) { 		this.gender = gender; 	}  	public String getMaritalStatus() { 		return maritalStatus; 	}  	public void setMaritalStatus(String maritalStatus) { 		this.maritalStatus = maritalStatus; 	}  } 

Name

 public class Name {  	private String firtsname; 	private String middlename; 	private String lastname;  	public Name() { 		super(); 	}  	public Name(String firtsname, String middlename, String lastname) { 		super(); 		this.firtsname = firtsname; 		this.middlename = middlename; 		this.lastname = lastname; 	}  	public String getFirtsname() { 		return firtsname; 	}  	public void setFirtsname(String firtsname) { 		this.firtsname = firtsname; 	}  	public String getMiddlename() { 		return middlename; 	}  	public void setMiddlename(String middlename) { 		this.middlename = middlename; 	}  	public String getLastname() { 		return lastname; 	}  	public void setLastname(String lastname) { 		this.lastname = lastname; 	} } 

ContactDetails

 public class ContactDetails {  	private String deskNumber; 	private String mobileNumber; 	EmergencyDetails emergencyDetails;  	public ContactDetails() { 		super(); 	}  	public ContactDetails(String deskNumber, String mobileNumber, EmergencyDetails emergencyDetails) { 		super(); 		this.deskNumber = deskNumber; 		this.mobileNumber = mobileNumber; 		this.emergencyDetails = emergencyDetails; 	}  	public EmergencyDetails getEmergencyDetails() { 		return emergencyDetails; 	}  	public void setEmergencyDetails(EmergencyDetails emergencyDetails) { 		this.emergencyDetails = emergencyDetails; 	}  	public String getDeskNumber() { 		return deskNumber; 	}  	public void setDeskNumber(String deskNumber) { 		this.deskNumber = deskNumber; 	}  	public String getMobileNumber() { 		return mobileNumber; 	}  	public void setMobileNumber(String mobileNumber) { 		this.mobileNumber = mobileNumber; 	} } 

EmergencyDetails

 public class EmergencyDetails {  	private String emergency_no1; 	private String emergency_no2; 	private String emergency_no3;  	public EmergencyDetails() { 		super(); 	}  	public EmergencyDetails(String emergency_no1, String emergency_no2, String emergency_no3) { 		super(); 		this.emergency_no1 = emergency_no1; 		this.emergency_no2 = emergency_no2; 		this.emergency_no3 = emergency_no3; 	}  	public String getEmergency_no1() { 		return emergency_no1; 	}  	public void setEmergency_no1(String emergency_no1) { 		this.emergency_no1 = emergency_no1; 	}  	public String getEmergency_no2() { 		return emergency_no2; 	}  	public void setEmergency_no2(String emergency_no2) { 		this.emergency_no2 = emergency_no2; 	}  	public String getEmergency_no3() { 		return emergency_no3; 	}  	public void setEmergency_no3(String emergency_no3) { 		this.emergency_no3 = emergency_no3; 	} } 

Now, let us create a Serialization Test

 public class XmlSerializationDemo2 {  	@Test 	public void serializationTest() {  		try {  			EmergencyDetails emergency = new EmergencyDetails("+91 894132345", "+91 8888221102", "+91 7223156288"); 			ContactDetails contdetails = new ContactDetails("00-428507", "+917823561231", emergency); 			Name empname = new Name("Trina", "Sophia", "William");  			// Converting a Java class object to a XML 			XmlMapper xmlMapper = new XmlMapper();  			String xmlString = xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Employees(empname, 					contdetails, 35, 100000.00, "Director", "trina@test.com", "female", "married")); 			System.out.println(xmlString);  			// write XML string to file 			String userDir = System.getProperty("user.dir"); 			File xmlOutput = new File(userDir + "\\src\\test\\resources\\XMLExample.xml"); 			FileWriter fileWriter = new FileWriter(xmlOutput); 			fileWriter.write(xmlString); 			fileWriter.close();  		} catch (  		JsonProcessingException e) {  		} catch (IOException e) {  		} 	} } 

Output

The newly created XML file is saved under src/test/resources as shown in the below image.

We have successfully serialized our Java object into XML and written it into an XML file.

In our serializationTest() function, we create an XmlMapper object, which is a child class to the ObjectMapper class used in JSON serialization. This class converts our Java Object into an XML output that we can now write to a file.

Hope it is useful. Happy Learning !!


This post is ad-supported