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 name="rule1" label="label1">
  <end-pattern include="true">.</end-pattern>
 <rule name="rule2" label="label2">

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:element maxOccurs="unbounded" ref="rule"/>
  <xs:element name="rule">
        <xs:element maxOccurs="unbounded" ref="match"/>
          <xs:element ref="start-pattern"/>
          <xs:element maxOccurs="unbounded" ref="end-pattern"/>
      <xs:attribute name="label" use="required" type="xs:NCName"/>
      <xs:attribute name="name" use="required" type="xs:NCName"/>
  <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"/>

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:

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