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 provided in Java SE 8 package 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 in a command window:

\fyicenter>\local\jdk-1.8.0\bin\xjc User.xsd

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.


Examples for JAXB (Java Architecture for XML Binding)

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

2018-05-08, 231👍, 0💬