Java, Software Development

JAXB Pre And Post-processing with Unmarshaller Listener

This post shows how to perform JAXB pre and post-processing with Unmarshaller Listener. For instance, you may want to compare the contents of an object before and after you unmarshal an XML. Another use-case is when you may need to store unmarshalled values to some list not mapped to any XML element. We can achieve it by creating a class that extends Unmarshaller Listener and overriding two methods. These methods are beforeUnmarshal and afterUnmarshal.

Software Requirements

  • Windows 10
  • Java 8 (Source Level = 1.8)
  • Eclipse Mars.2 Release (4.5.2)

JAXB Unmarshaller Listener

The Unmarshaller Listener is an abstract class available in java.xml.bind.package. It has two methods.

Pre And Post-Processing Person Unmarshal Listener

The PersonUnmarshallListener is our listener implementation that prints some texts and stores the name value to a list. For instance, the afterUnmarshal prints out “AFTER UNMARSHAL”, the object’s content, and then holds the person’s name on a list. For the beforeUnmarshal method, it prints out “BEFORE UNMARSHAL” and the contents of the initial object.

JAXB Model and Test XML For Pre and Post-Processing

Our Java JAXB class represents the contents of our test XML. Then, we have a list field that we annotated with @XmlTransient. As a result, this field will not be to any element in the test XML, and we will use it to store the name of the Person object.

Below is our test XML.

First, we must instantiate our listener and set it as the unmarshaller’s listener.

When we run the codes, we get the following sample output. We can see the content of the JAXB object after pre and post-processing using the Unmarshaller Listener.

Download the codes for JAXB Pre and Post-processing using Unmarshaller Listener

You may download the codes from this GitHub repository that do JAXB pre and post-processing on an XML using Unmarshaller Listener.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like