Creating Java classes from an XML schema

This is actually part of a set of three posts taking an XSD (XML Schema), generating the Java classes for it, then we’ll create a server using CXF that will support both JSON and XML responses, finally we’ll create a client that can switch between the two.

Step 1

Step 1 is the easy bit – so we have an xsd (we’ll use a Sample XSD recreated below)

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"   
           xmlns:tns="http://tempuri.org/PurchaseOrderSchema.xsd"   
           targetNamespace="http://tempuri.org/PurchaseOrderSchema.xsd"   
           elementFormDefault="qualified">  
 <xsd:element name="PurchaseOrder" type="tns:PurchaseOrderType"/>  
 <xsd:complexType name="PurchaseOrderType">  
  <xsd:sequence>  
   <xsd:element name="ShipTo" type="tns:USAddress" maxOccurs="2"/>  
   <xsd:element name="BillTo" type="tns:USAddress"/>  
  </xsd:sequence>  
  <xsd:attribute name="OrderDate" type="xsd:date"/>  
 </xsd:complexType>  
  
 <xsd:complexType name="USAddress">  
  <xsd:sequence>  
   <xsd:element name="name"   type="xsd:string"/>  
   <xsd:element name="street" type="xsd:string"/>  
   <xsd:element name="city"   type="xsd:string"/>  
   <xsd:element name="state"  type="xsd:string"/>  
   <xsd:element name="zip"    type="xsd:integer"/>  
  </xsd:sequence>  
  <xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>  
 </xsd:complexType>  
</xsd:schema>  

I’ve saved this as sample.xsd.

Now from a command prompt run

xjc -p com.putridparrot.sample sample.xsd

XJC will generate Java source code in the package (-p) com.putridparrot.sample, so you should see four files. Two are our complexTypes, one is package-info.java which allows us to apply package level annotations and the final one is ObjectFactory.java which is a utility class/factory for creating types and (as it says in the comments within the file)

“allows you to programatically construct new instances of the Java representation for XML content”