Hello, guys. This is my first time using English in my tutorial. Hope you guys do not miss any important stuff here hahahaha. Let's do it!
In this chance I'm gonna show you how to generate Java classes from XSD file with very detail steps. As we know, XSD is XML Schema Definition which is used to describes the structure of an XML document. For example, I have very simple XSD file that represents of the data of Employee as shown below.
1 2 3 4 5 6 7 8 9 10 11 | <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified" > <xs:element name="Employee"> <xs:complexType> <xs:sequence> <xs:element name="Name" type="xs:string"/> <xs:element name="Phone" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> |
So, as I know, there are two ways to generate Java classes from XSD which are JAXB and Castor. JAXB is the Java Architecture XML Binding which is the part of Java itself. When you install JDK you have it all. While Castor is an open source data binding framework. That's it. Maybe if you know the other methods for XML Binding, you can put your comment below. Okay, don't take it too long. Let's start it!
JAXB
- Prepare your XML Schema (XSD file). You can use my example as yours
- Open the Command Prompt and point to the directory of your XSD file. In this demonstration, I put my XSD file at C:/Documents
- Use the command below and press Enter. Notes: please command "xjc" to see all the xjc parameter options. -p option is to define the package of your java project.
C:\Documents>xjc -p test.java.generation Employee.xs
- Then the Java class of Employee is generated including ObjectFactory.java. ObjectFactory contains factory methods for each Java content interface and Java element interface generated in the com.test.xml package. An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content
- Now your Java classes are ready to use for your next development. Please refer to your defined package above to see the result of the generated java classes.
- Simply copy and paste those classes to your Java project
Castor
There's not much difference steps between JAXB and Castor. Just follow the steps above and change the command line below:
C:\Documents>java -cp castor-0.9.5.3p3-xml.jar;xercesImpl-2.9.1.jar; org.exolab.castor.builder.SourceGenerator -i ../files/Employee.xsd -package com.xmlinclude.castor
There's no results print out in our console. If your execution return no errors, it means your java classes generated successfully and your java classes are ready to use.
Notes:
-i: option to define your file path
-package: option to define your class package
Hope this article helps you :)
In the next article I will give you a tutorial how to generate Java classes if your XSD file has include tag (xi:include)