How to generate java class from xml schema xsd using jaxb in eclipse

Let us discuss how to generate or create java class from xml schema xsd using jaxb in eclipse with below example.

Steps:

1. Create a new JAXB project. File -> New -> Other -> JAXB -> JAXB Project.
jaxb1
 
2. Enter the project name and click on Finish button.
jaxb2
 
3. Download JAXB Jar and JAXB-XJC jar files and include in class path.
jaxb11
 
4. Create package which will contain xsd file.
jaxb3
 
5. Create package which will contain java classes.
jaxb4
 
6. Create xsd file.
jaxb5
 
7. Copy the below code into xsd file.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
 
  <xs:element name="student" type="student"/>
  <xs:element name="address" type="address"/> 
 
  <xs:complexType name="address">
    <xs:sequence>
      <xs:element name="addressLine1" type="xs:string" minOccurs="0"/>
      <xs:element name="addressLine2" type="xs:string" minOccurs="0"/>
      <xs:element name="city" type="xs:string" minOccurs="0"/>
      <xs:element name="state" type="xs:string" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType> 
 
  <xs:complexType name="student">
    <xs:sequence>
      <xs:element name="firstName" type="xs:string" minOccurs="0"/>
      <xs:element name="lastName" type="xs:string" minOccurs="0"/>
       <xs:element name="className" type="xs:string" minOccurs="0"/>
      <xs:element name="rollNo" type="xs:string" minOccurs="0"/>
      <xs:element ref="address" minOccurs="0"/>      
    </xs:sequence>
  </xs:complexType>
 
</xs:schema>

8. Right click on your package -> New -> Other -> JAXB -> JAXB Classes from Schema.
jaxb7
 
9. Specify project for new Java classes and click on Next.
jaxb8
 
10. Select schema from which java classes have to generated and click on Next.
jaxb9
 
11. Specify package for new Java classes and click on Finish.

jaxb10
 

On Console:

parsing a schema...
compiling a schema...
com\w3spoint\javaclass\Address.java
com\w3spoint\javaclass\ObjectFactory.java
com\w3spoint\javaclass\Student.java

Download this example.
 
Next Topic: How to generate xml schema xsd from java class using jaxb in eclipse.
Previous Topic: JAXB unmarshalling – convert xml into java object example.

 

Content Protection by DMCA.com
Please Share