Saturday, 20 August 2016

Jaxb: Generate classes from XML schema using xjc tool

By using xjc command line tool, you can map xml schema to Java classes.

You can download xjc from following command.


Use following command to map xml schema to classes.

xjc.sh xsdFile


employees.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

 <!-- Schema for simple elements -->
        <xs:element name="id" type="xs:integer" />
 <xs:element name="firstname" type="xs:string" />
 <xs:element name="middlename" type="xs:string" />
 <xs:element name="lastname" type="xs:string" />
 <xs:element name="age" type="xs:integer" />
        <xs:element name="salary" type="xs:decimal" />
        <xs:element name="married" type="xs:string" />
        <xs:element name="department" type="xs:string" />
        <xs:element name="pjtname" type="xs:string" />
 <xs:element name="from" type="xs:date" />
 <xs:element name="to" type="xs:date" />
        
 <!-- Schema for element name -->
 <xs:element name="name">
  <xs:complexType>
   <xs:sequence>
                            <xs:element ref="firstname" />
                            <xs:element ref="middlename" />
                            <xs:element ref="lastname" />
                            <xs:element ref="age" />
                            <xs:element ref="salary" />
                            <xs:element ref="married" />
   </xs:sequence>
  </xs:complexType>
 </xs:element>

         <!-- Schema for element project -->
 <xs:element name="project">
  <xs:complexType>
   <xs:sequence>
                            <xs:element ref="department" />
                            <xs:element ref="pjtname" />
                            <xs:element ref="from" />
                            <xs:element ref="to" />
   </xs:sequence>
  </xs:complexType>
 </xs:element>

         <!-- Schema for element employee -->
 <xs:element name="employee">
  <xs:complexType>
   <xs:sequence>
                            <xs:element ref="id" />
                            <xs:element ref="name" />
                            <xs:element ref="project" maxOccurs="unbounded" />
   </xs:sequence>
  </xs:complexType>
 </xs:element>

          <!-- Schema for element employees -->
 <xs:element name="employees">
  <xs:complexType>
   <xs:sequence>
                            <xs:element ref="employee" maxOccurs="unbounded" />
   </xs:sequence>
  </xs:complexType>
 </xs:element>
 
</xs:schema>

$ ./xjc.sh ../../employees.xsd 
parsing a schema...
compiling a schema...
generated/Employee.java
generated/Employees.java
generated/Name.java
generated/ObjectFactory.java
generated/Project.java



Previous                                                 Next                                                 Home

No comments:

Post a Comment