top of page
Search

JAXB marshal and unmarshal XML with schema validation example

  • Writer: Wynn Teo
    Wynn Teo
  • Sep 22, 2017
  • 2 min read

In this article, I will shows how to use JAXB marshal and unmarshal XML and Java objects together with schema xsd validation. JAXB stands for Java Architecture for XML Binding which allows Java developers to marshal Java objects into XML content and unmarshal XML content back to Java objects. JAXB is bundled in JDK1.6 and above, with that there is no additional library required. If you are using JDK version < 1.6, you are required to import “jaxb-api.jar” and “jaxb-impl.jar” into your project classpath.


1. JAXB XML file

Firstly, we prepared a Car schema named it as car.xsd and Car XML file named it as car.xml



2. Car object class

Next, we need to have a car object Java class then add in the XML annotation to instruct JAXB map the XML tag to corresponding Java attribute accordingly. If you have alot attributes, you may used @XmlAccessorType(XmlAccessType.FIELD) with this annotation, you no need to add in the @XmlElement at each get method. But do take note, the XML tag name must match exactly the same as your object attribute name. I created a ‘Images’ class. If you refer back to the XML file, you may notice the <Images> and <ImageList> layer are extra. How to skip the layer and grab the <Image> list? Take a look at the trick below:




The trick is @XmlElementWrapper(name = “ImageList”), this annotation add a grouping element to wrap the <Image> list.

3. Convert XML to Object – Unmarshal

Now we going to convert our car.xml into Java Car object. To convert xml into java object, we used Unmarshaller. Before converting, set the schema so that it will validate the car.xml.






Run the program, the output produced would be something like:





4. Convert Java Object to XML – Marshal

Now we going to convert the Java car object into XML. To convert xml into java object, we used Marshaller.





Take note that JAXB does not guarantee the order in which the attributes will show first. But if the marshaller set the schema, it will complains the order does not match. One thing we can overcome this issue is using @XmlType to set the attributes sequence.





Comments


bottom of page