Generate Java Code from XML Schema with XJC


How to generate Java code from XML Schema with XJC (XML to Java Compiler)?



If you have an XML Schema, you can create Java code to represent complex XML elements as Java classes manually according to mapping rules given in the JAXB API specification.

But you can also using the XJC (XML to Java Compiler) tool to generate Java code automatically for you as presented in this tutorial:

1. Create an XML schema document called User.xsd:

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) -->
<xsd:schema xmlns:xsd="">
  <xsd:element name="User">
        <xsd:element name="BirthDate" type="xsd:date" />
        <xsd:element name="Name" type="xsd:string" minOccurs="1" maxOccurs="1"/>
        <xsd:element name="Sex">
            <xsd:restriction base="xsd:string">
              <xsd:enumeration value="Male" />
              <xsd:enumeration value="Female" />
    <xsd:attribute name="ID" type="xsd:int" use="required"/>

2. Run XJC tool from the JAXB API Reference Implementation package. The script,, needs to be modified as shown in the last tutorial.

fyicenter$ ../jaxb-ri/bin/ User.xsd  

  Java major version: 15
  parsing a schema...
  compiling a schema...

You get Java code of 2 Java classes:

  • generated.User - Represents the complex XML element type defined in User.xsd.
  • generated.ObjectFactory - Represents a factory class to help you to create User objects quickly. - Java Data Type Class Generated by XJC

What Is XJC (XML to Java Compiler)

Examples for JAXB (Java Architecture for XML Binding)

⇑⇑ FAQ for jaxb-*.jar - Java Architecture for XML Binding

2018-05-08, 1170🔥, 0💬