Generate Java Code from XML Schema with XJC

Q

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

✍: FYIcenter.com

A

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) FYIcenter.com -->
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="User">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="BirthDate" type="xsd:date" />
        <xsd:element name="Name" type="xsd:string" minOccurs="1" maxOccurs="1"/>
        <xsd:element name="Sex">
          <xsd:simpleType>
            <xsd:restriction base="xsd:string">
              <xsd:enumeration value="Male" />
              <xsd:enumeration value="Female" />
            </xsd:restriction>
          </xsd:simpleType>
        </xsd:element>
      </xsd:sequence>
    <xsd:attribute name="ID" type="xsd:int" use="required"/>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

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

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

  Java major version: 15
  parsing a schema...
  compiling a schema...
  generated/ObjectFactory.java
  generated/User.java

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.

 

User.java - 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, 1245🔥, 0💬