XML to XSD to Java Generation Using JAXB and Trang

In this blog post I am going to explain how Java code can be generated from XML using xjc and Trang.

Trang is a Multi-format schema converter based on RELAX NG. You can download the latest version of Trang from here.

xjc stands for Java Architecture for XML Binding Compiler, JDK 1.6 comes with xjc compiler which can be found under <java_home>/bin as xjc.exe(for Windows).

Now, suppose I have a XML file called rules.xml as follows:
<rule-config>
 <rule name="rule1" label="label1">
  <start-pattern>name:</start-pattern>
  <end-pattern include="true">.</end-pattern>
 </rule>
 <rule name="rule2" label="label2">
  <match>name1</match>
 </rule>
</rule-config>

First we will generate a schema for rules.xml using trang. Execute the below command:
java -jar trang.jar rules.xml rules.xsd

This will generate an XSD named rules.xsd

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:element name="rule-config">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" ref="rule"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="rule">
    <xs:complexType>
      <xs:choice>
        <xs:element maxOccurs="unbounded" ref="match"/>
        <xs:sequence>
          <xs:element ref="start-pattern"/>
          <xs:element maxOccurs="unbounded" ref="end-pattern"/>
        </xs:sequence>
      </xs:choice>
      <xs:attribute name="label" use="required" type="xs:NCName"/>
      <xs:attribute name="name" use="required" type="xs:NCName"/>
    </xs:complexType>
  </xs:element>
  <xs:element name="match" type="xs:NCName"/>
  <xs:element name="start-pattern" type="xs:NMTOKEN"/>
  <xs:element name="end-pattern">
    <xs:complexType mixed="true">
      <xs:attribute name="include" type="xs:boolean"/>
    </xs:complexType>
  </xs:element>
</xs:schema>


Now, we will generate Java code from this XSD using xjc.exe. Run the below command:
xjc.exe -p com.sample.config rules.xsd

This will generate the following Java classes:
ObjectFactory.java
RuleConfig.java
Rule.java
EndPattern.java

Now you have all the classes needed for unmarshalling the xml file!

JAXBContext jc = JAXBContext.newInstance("com.sample.config");
Unmarshaller u = jc.createUnmarshaller();
RuleConfig ruleConfig = (RuleConfig)u.unmarshal(
   new FileInputStream("rules.xml"));

Simple, isn't it?

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to our feed and get articles like this delivered automatically to your feed reader? Like our Facebook Page.

Post a Comment (0)
Previous Post Next Post