Using JAXB to generate XML from XSD

This is a post originally published by Mohamed Sanaulla from Experiences Unlimited, our latest JCG partner. Mohamed explains how to use JAXB to generate XML from a given XSD.

(NOTE: The original post has been slightly edited to improve readability)

We can use JAXB to marshal the Java objects into XML using the given Schema and vice versa- unmarshal XML into Java objects. The XML schema can be specified in DTD, XSD or other format.

The tool “xjc” can be used to generate the annotated Java classes from the XSD schema. One can download the Java Web Services Developer Pack (WSDP), it includes the JAXB implementation tools required. Here I will throw light on how to generate XML dynamically.

The sample XSD being used is:

- expense.xsd

<?xml version="1.0"?>
<xs:schema xmlns:xs="">
<xs:element name="expenseReport" type="ExpenseT" />
<xs:complexType name="ExpenseT">
        <xs:element name="user" type="UserT"/>
        <xs:element name="items" type="ItemListT"/>
<xs:complexType name="UserT">
        <xs:element name="userName" type="xs:string" />
<xs:complexType name="ItemListT">
         <xs:element name="item" type="ItemT" maxOccurs="unbounded"/>
<xs:complexType name="ItemT">
         <xs:element name="itemName" type="xs:string" />
         <xs:element name="purchasedOn" type="xs:string" />
         <xs:element name="amount" type="xs:decimal" />

Now we use the xjc tool to generate the corresponding Java classes. The generated Java classes are annotated appropriately. I am not going into details about the annotation of the classes, cause it would make things complicated.

xjc.exe expense.xsd

By default the command generates the Java classes in a directory named “generated”. There are lot of options which can be used with xjc and one can have a look at using

xjc -help

The below Main class uses the generated classes for creating the XML.


package generated;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.math.BigDecimal;
public class Main
    public static void main(String[] args) throws JAXBException
        ObjectFactory factory = new ObjectFactory();
        UserT user = factory.createUserT();
        ItemT item = factory.createItemT();
        item.setItemName("Seagate External HDD");
        item.setPurchasedOn("August 24, 2010");
        item.setAmount(new BigDecimal("6776.5"));
        ItemListT itemList = factory.createItemListT();
        ExpenseT expense = factory.createExpenseT();
        JAXBContext context = JAXBContext.newInstance("generated");
        JAXBElement<ExpenseT> element = factory.createExpenseReport(expense);
        Marshaller marshaller = context.createMarshaller();

In the above XSD, we see that there are few complex types declared. These complex types generate in to Java classes. The child elements and attributes become the properties of the class and they are provided with getters and setters. One cannot directly create an instance of such classes, i.e. cannot call new on them. Whenever we compile a XSD, there is a ObjectFactory class generated – this is the factory for creating the instances of the XSD Complex types (Lines-17,19, 24, 27 in the above Java class).

Once we get the instance we populate the properties with corresponding data using the setters provided with the class. Also note that a complex element can have many complex elements as the members of the class. In that case we use the factory to get the instance of the complex elements and then use the setters of the outer complex element.

For example: In the above XSD, ExpenseT is a complex type which consists of UserT and a list of ItemT (ItemListT). In the above Java class – Lines 27,28,29 – we are creating an instance of ExpenseT and then using the setters to set the values of the UserT and ItemListT. The RootElement is created by calling createExpenseReport() for the factory. The name of the method is influenced by the name of the root element and the return type and the argument type of the method is same as that of the type of root element.

Once we have set the values for the different elements, attributes which are to go into the XML, its now time to actually generate the XML. We must have a Marshaller (to get XML from the Java objects) or an Unmarshaller (to get Java objects from XML).

We would need a Marshaller – which can be obtained from the JAXBContext instance. Lines 31,32 obtain an instance of Marshaller. Different properties can be set for the marshaller and in the above code we are setting the jaxb.formatted.output as true, which means that the XML obtained is neatly formatted making is readable to the user.

Different supported properties are:

  • jaxb.encoding
  • jaxb.formatted.output
  • jaxb.schemaLocation
  • jaxb.noNamespaceSchemaLocation
  • jaxb.fragment

<instance_of_marshaller>.marshal() is the method used to generate the XML. Its is overloaded to accept the following output mechanisms:

The generated XML is shown below:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
       <itemName>Seagate External HDD</itemName>
       <purchasedOn>August 24, 2010</purchasedOn>

Related Articles:

Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

4 Responses to "Using JAXB to generate XML from XSD"

  1. Taq Wave says:

    Hi, your generated XML is missing the namespace information, how do you unmarshal the XSD so that marshalling back to XML has the namespaces?

  2. jcode says:

    Great post!
    I have a question for you, before create xml I want to validate it with xsd file.

  3. rokonoid says:

    is there any tool that can do the reverse, i mean xml to xsd ?

Leave a Reply

× 1 = two

Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books