xml schema to Java object and Java object to schema conversion with schemagen and xjc

In this article, we will use schemagen and xjc utilities for xml schema to java object and java object to xml schema conversion.

 

Both these utilities are included as part of JDK.

 

schemagen utility can generate an XML Schema instance from a POJO.

 

xjc can generate java classes from a XML schema.

 

schemagen

This can be invoked from command line as follows:

 

schemagen [-options]

 

For example, lets create a java project and create a class HelloWorld.java in package com.topjavatutorial inside it.

package com.topjavatutorial;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="Hello")
public class HelloWorld {
  
  private String name;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}


Now if we go to the path where this file is present and run schemagen as follows, it will create a xml schema file in same path.

The annotation @XmlRootElement indicates that the outermost element in the schema will be named Hello.

 

Here is the schemagen command :

schemagen -cp . HelloWorld.java

This will create the xml schema file schema1.xsd in the same path.. Here is how the generated schema will look like:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="helloWorld" type="helloWorld"/>

  <xs:complexType name="helloWorld">
    <xs:sequence>
      <xs:element name="name" type="xs:string" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>


 

xjc

 
This can be invoked from command line as follows:

 

xjc[-options]

Let’s use the schema file generated using schemagen to create the java file.

For this, execute the following xjc command from the path where schema1.xsd is present :

xjc -cp . schema1.xsd
 
xjc

Now the generated package will contain the java files.
 

© 2015, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags