JAXB Marshalling Java to Xml Binding Example

What is JAXB Marshalling?

JAXB Marshal UnMarshal

Using JAXB (Java architecture for XML binding) we can perform Marshalling  – for converting a java object to XML and UnMarshalling –  for converting a XML to Java object.  JAXB defines API for reading and writing Java objects to and from XML documents. It is easy to use comparatively SAX and DOM, as we don’t need to know in detail XML parsing techniques.


JAXB Marshalling Example – Java to XML Binding

We will create a java program to perform marshalling operation to convert Java object to XML. In this programme we will Company, Department and Employee Java object which will be used to convert to and from XML.  For handling complex types that may not be directly available in JAXB API we need to write an adapter to indicate JAXB how to manage the specific type. We are going to explain this by using an example of marshaling for an element of the type java.time.LocalDate. We will create DateFormatAdapter which will control conversion logic LocalDate field of Company.java class during Marshalling.


1)  Company.java


The class above contains some JAXB annotations that allow us to indicate what XML nodes we are going to generate. For this purpose we are using the annotations

  • @XmlRootElement as root element.
  • @XmlType to control order of appearance in the XML.
  • @XmlElement in combination with setter methods to provide a different name in xml file.
  • @XmlAttribute to pass attributes to the XML nodes. These attributes can have properties like to be required or not.
  • @XmlElementWrapper It generates a wrapper around an XML representation, intended to be used with collections.
  • @XmlJavaTypeAdapter It implements XMlAdapter for handling custom marshaling and Unmarshalling for a particular field.

2) Department.java


3) Employee.java


4) DateFormatAdapter.java


5) MarshallingJavaToXMLJaxbDemo1.java

Console Output of the above programme:




One Reply to “JAXB Marshalling Java to Xml Binding Example”

  1. i have data coming and i have to convert those data into xml and have to pass as it is, for example :
    i have to convert this above data into xml and has to pass as it is after conversion as a response using rest

Leave a Reply