Using JAXB to generate XML from the Java, XSD
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” is used to generate the annotated Java classes from the XSD schema. One can download the Java WSDP from here, it includes the JAXB implementation tools required. Here I will throw light on how to generate XML dynamically. Even I havent gone in depth with JAXB, but I found this really useful and thought of sharing it in the blog.
The sample XSD being used is: expense.xsd
<?xml version="1.0"?></div>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="expenseReport" type="ExpenseT" />
<xs:complexType name="ExpenseT">
<xs:sequence>
<xs:element name="user" type="UserT"/>
<xs:element name="items" type="ItemListT"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="UserT">
<xs:sequence>
<xs:element name="userName" type="xs:string" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="ItemListT">
<xs:sequence>
<xs:element name="item" type="ItemT" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="ItemT">
<xs:sequence>
<xs:element name="itemName" type="xs:string" />
<xs:element name="purchasedOn" type="xs:string" />
<xs:element name="amount" type="xs:decimal" />
</xs:sequence>
</xs:complexType>
</xs:schema>
You can read about XSD here.
Now we use the xjc tool to generate corresponding Java classes. The generate java classes are annotated appropriately. Am not going into 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- Main.java 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();
user.setUserName("Sanaulla");
ItemT item = factory.createItemT();
item.setItemName("Seagate External HDD");
item.setPurchasedOn("August 24, 2010");
item.setAmount(new BigDecimal("6776.5"));
ItemListT itemList = factory.createItemListT();
itemList.getItem().add(item);
ExpenseT expense = factory.createExpenseT();
expense.setUser(user);
expense.setItems(itemList);
JAXBContext context = JAXBContext.newInstance("generated");
JAXBElement<ExpenseT> element = factory.createExpenseReport(expense);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty("jaxb.formatted.output",Boolean.TRUE);
marshaller.marshal(element,System.out);
}
}
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 the getters and setters. One cannot directly create the instance of such classes i.e cannot call new on them. When ever we compile a XSD, there is a ObjectFacotry 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 what happens 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- am 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 an 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 properties supported 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:
- org.xml.sax.ContentHandler
- org.w3c.dom.Node
- javax.xml.transform.Result
- java.io.Writer
- java.io.OutputStream
- javax.xml.stream.XMLStreamWriter
- javax.xml.stream.XMLEventWriter
The xml generated is shown below:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<expenseReport>
<user>
<userName>Sanaulla</userName>
</user>
<items>
<item>
<itemName>Seagate External HDD</itemName>
<purchasedOn>August 24, 2010</purchasedOn>
<amount>6776.5</amount>
</item>
</items>
</expenseReport>
PS: I havent gone much into the details of JAXB. This is just the overview of how one can generate XML confirming to the schema.
Read about How to Unmarshall the XML data.
No related posts.
14 Responses to Using JAXB to generate XML from the Java, XSD
Connect to us …
Archives
- May 2013 (10)
- April 2013 (6)
- March 2013 (6)
- January 2013 (5)
- November 2012 (2)
- September 2012 (1)
- July 2012 (5)
- June 2012 (1)
- May 2012 (4)
- April 2012 (7)
- March 2012 (2)
- February 2012 (4)
- December 2011 (2)
- November 2011 (4)
- October 2011 (2)
- September 2011 (1)
- August 2011 (1)
- July 2011 (1)
- June 2011 (1)
- May 2011 (1)
- April 2011 (1)
- February 2011 (4)
- December 2010 (3)
- November 2010 (2)
- September 2010 (2)
- August 2010 (3)
- May 2010 (2)
- March 2010 (6)
- December 2009 (1)
- November 2009 (3)
- July 2009 (6)
- June 2009 (3)
- May 2009 (1)
- April 2009 (6)
- March 2009 (1)
- January 2009 (1)
- December 2008 (8)
- November 2008 (5)
- October 2008 (6)
- September 2008 (4)
- August 2008 (8)
- July 2008 (19)
- June 2008 (29)
- May 2008 (27)
- April 2008 (11)
- March 2008 (8)
- February 2008 (22)
- January 2008 (3)
Send To Readmill
Send to ReadmillRecent Posts
- Parsing XML in Groovy using XmlSlurper
- Parsing XML using DOM, SAX and StAX Parser in Java
- How to create ADF TreeTable programmatically?
- Book review: The Object-Oriented Thought Process
- How to show links in ADF Messages
- Runtime Polymorphism in Java
- Understanding RowKey values in ADF TreeTable
- Train Wreck Pattern – A much improved implementation in Java 8
- Converting a List into comma separated value string in Java
- A simple application of Lambda Expressions in Java 8
Disclaimer
Some of the links contained within this site have my referral id, which provides me with a small commission for each sale. Thank you for your support.










When I unmarshall xml, I am not able to find expenseReport object.
Can you post unmarshall code also?
That would take some time. Can you post the code here so that I can take a look and help you?
I have posted the Unmarshall code at: http://blog.sanaulla.info/2013/01/25/using-jaxb-to-generate-java-objects-from-xml-document/
Hi Mohamed,
Nice post. I noticed your information as to where to obtain a JAXB implementation is out date. Since Java SE 6 an implementation of JAXB has been included in the JRE/JDK. Also since JAXB is a specification (JSR-222), there are several implementations available:
- Metro JAXB
- EclipseLink JAXB (MOXy)
- Apache JaxMe
-Blaise
Thanks a lot for throwing light on that.
JAXBElement element = factory.createExpenseReport(expense);
This function is not available with argument.
It is available with 0 arguments and moreover the return type doesn’t match.
Class casting doesn’t help.
Please help me…
your code is not good..
plz improve..
Can you please tell me what good code is?
Thanks for the post. It can be done from eclipse also. Right click the xsd > source > generate > xml > select root > finish.
Nice post!
Can you specify out if the code in Main method is thread-safe?
Thanks!
Thanks , this post helped me a lot as i had a similar requirement to create xml string using xsd .
[...] did some research and found that ‘jaxb’ could do it. And I found some example too, but the problem is, almost all the examples uses ‘xjc’ tool to do this. But I want a [...]
hi can you please tell me how to partially unmarshal using jaxb
[...] sometime back I had written about Using JAXB to generate XML from the Java, XSD. And now I am writing how to do the reverse of it i.e generating Java objects from the XML [...]