How to Generate XML from XSD in Java? The Answer

learn how to generate xml from xsd in java

One of your core Java programming assignments can be to generate an XML from XSD. Before we get into the basics of how to generate an XML file from an XSD in Java, we need to go through some definitions first. In computer programming, an XML file is an acronym that stands for Extensible Mark-up Language. This file format is used to share both the data and format of the World Wide Web and other intranets using ASCII. It describes content in terms of the data by placing mark-up tags which will indicate the type of data present. Another feature of an XML file is that it is considered extensible. That means that the mark-ups present can be self-defining and also unlimited in number.

What Is XSD File in Java?

On the other hand, an XSD file can be considered the backbone of the XML file. That’s because, without XSD files, an XML file is just a bunch of free elements and a couple of attributes with zero use. Now, the XSD file specifically works to define which attributes and elements are allowed and in what pertaining order.

Normally, when we compile XML schema, the API consists of two types of categories which include:

  • built-in designs that mimic those in the schema
  • and those that are generated utilizing the user-derived schema

Normally, the API created from schema is a means of accessing the XML instances on basis of the schema present. The XMLBeans API also gives you a method of acquiring information concerning the system type.

Now that we have a solid foundation on the type of files we are dealing with, here is a step by step analysis on how to generate XML from XSD in Java and where to put XSD in Java project.

How to Generate XML from XSD in Java: Getting Started

To get started, we will utilize the JAXB to transform Java objects into XML and also to transform XML into Java objects; more specifically XSD. Below is a comprehensive step by step code. Here we are using 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 now utilize the xjc tool to create the required Java classes. These classes will automatically have the proper annotation.

xjc.exe.expense.xsd

The above command will by default create Java classes in the directory specified by the name generated.

Thus, below is the class Main.java which will thereby be used together with the generated classes to create the XML.

xsd to xml generator
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);
}
}

As observed in the XSD, we can notice that there are a number of complex types that have been declared. These complex types are what are created into the Java classes. The attributes and respective child elements further become the property of the class and are further supplied by the setters and getters. One can therefore not generate directly the instance of such a class. So whenever we compile an XSD, an ObjectFactory is normally created which will further generate instances that will be used in the XSD Complex types. Once the instance has been generated, you can further populate the properties with data utilizing the setters given by the class.

 

It is important to note one thing before we move further. And that is that a complex element can acquire multiple complex elements similar to those of the members within a class. Therefore, we will use the factory in order to obtain an instance of complex elements; then proceed by utilizing the outer complex element setters. For example, in the above code, Expense T is a complex which in it there is a UserT and ItemT. The RootElement is further generated utilizing the createExpenseReport(). Note that the method’s name is actually determined by the root element’s name, the return type, and further the argument type.

java xml jokes

After we have given the different elements and attributes their set values, they are then transferred to the XML which is then generated. It is compulsory for us to have a Mashaller that will derive the XML from Java objects; alternatively, an Unmarshaller should be present that will obtain Java objects from XML. We will also require a Marshaller whose function will be to derive the JAXBContext instance. The properties of this marshaller can then be modified according to our code. We will further set the jabx.formatted.output as true; meaning that our obtained XML will be easy to read for the user.

The various properties that can be supported include:

  • jabx.fragment
  • jabx.formatted.output
  • jabx.encoding
  • jabx.schemaLocation
  • jabx.noNamesspaceSchemaLocation

Learn the niceties of sorting an array in Java right now!

The method .marshal() is what is utilized to derive the XML. It is further overloaded to give a green light to the following output mechanisms.

  • javax.xml.stream.XMLEventWriter
  • org.xml.sax.ContentHandler
  • java.xml.xtream.XML.StreamWriter
  • org.w3c.dom.Node
  • java.io.OutputStream
  • java.xml.transform.Result
  • java.io.Writer

Therefore, the XML we can create is as shown in a programming code 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>

Now that you have a solid foundation on where to get started with XML to XSD, we encourage you to try out the above codes to improve your practice on a more advanced level. If that’s not enough and you have an insatiable desire to learn more about converting files, you can get in touch with us. We will help you learn more on XML and XSD and how to write codes faster and in a more skillful manner.

Have no idea how to generate XML from XSD in java? Feel free to get in touch with us and we will be more than happy to get started!