Introduction
As you know XML documents play a very significant role in modern projects and product development. Apart from XML documents we encounter jargons like XML schema, XSD and DTD files. There are certain situations where we need to convert a XML document to DTD format or XSD format. There are commercial tools available in the market to provide more clarity on XML, XSD or DTD files. Now the question is whether we can do it using Java. In this article, I provide a glimpse at the Java API for doing the basics of XML file conversion using Java APIs.
Technicalities
This article is neither about XML, XSD or DTD nor about their features and advantages. In this article, I will present how to generate various XML, XSD or DTD files using Java. As a Java developer we all know how to parse or play with XML files to gather information. In this article, we will learn how to convert XML to XSD or DTD using Java classes. As you know Java provides the API called JAXB through which we can generate a XML document through classes. However, JAXB provides other features also that are unknown to us. This article provides brief outlines of the following items:
- Java Class to XML
- Java Class to XSD
- XML to XSD
- XML to DTD
- XSD to Java Classes
- DTD to Java Classes
Java Class to XML
According to JAXB, you can write a plain Java Bean (POJO) and provide the simple JAXB annotations in the class, fields and method levels. You need to populate the Java Bean and provide to JAXB how to generate the XML document. The generation of the XML document from the Java class is called Marshalling. Let us see a small piece of code to become familiar with the JAXB annotations.
- package com.ddlab.xml.jaxb.beans;
- import javax.xml.bind.annotation.XmlElement;
- import javax.xml.bind.annotation.XmlElementRef;
- import javax.xml.bind.annotation.XmlRootElement;
- import javax.xml.bind.annotation.XmlType;
- /**
- * The Class Organisation is used as Java Bean which is root of the XML element.
- * This class is provided with JAXB annotations to generate XML and XSD file
- * smoothly.
- * @author <a href="mailto:[email protected]">Debadatta Mishra</a>
- * @since 2013
- */
- @XmlRootElement(name = "Organisation")
- @XmlType(propOrder = { "name", "totalEmps", "descn", "turnOver", "emp" })
- public class Organisation {
- /** The name. */
- private String name;
- /** The descn. */
- private Description descn;
- /** The total emps. */
- private int totalEmps;
- /** The turn over. */
- private double turnOver = 0d;
- // ~~ Getter and Setter Methods
- /**
- * Gets the descn.
- * @return the descn
- */
- @XmlElement(name = "Description")
- public Description getDescn() {
- return descn;
- }
- /**
- * Sets the descn.
- *
- * @param descn
- * the new descn
- */
- public void setDescn(Description descn) {
- this.descn = descn;
- }
- /** The emp. */
- private Employees emp;
- /**
- * Gets the emp.
- *
- * @return the emp
- */
- @XmlElementRef(type = Employees.class)
- public Employees getEmp() {
- return emp;
- }
- /**
- * Sets the emp.
- *
- * @param emp
- * the new emp
- */
- public void setEmp(Employees emp) {
- this.emp = emp;
- }
- /**
- * Gets the name.
- *
- * @return the name
- */
- @XmlElement(name = "Name")
- public String getName() {
- return name;
- }
- /**
- * Sets the name.
- *
- * @param name
- * the new name
- */
- public void setName(String name) {
- this.name = name;
- }
- /**
- * Gets the total emps.
- *
- * @return the total emps
- */
- @XmlElement(name = "TotalEmployees")
- public int getTotalEmps() {
- return totalEmps;
- }
- /**
- * Sets the total emps.
- *
- * @param totalEmps
- * the new total emps
- */
- public void setTotalEmps(int totalEmps) {
- this.totalEmps = totalEmps;
- }
- /**
- * Gets the turn over.
- *
- * @return the turn over
- */
- @XmlElement(name = "TurnOver")
- public double getTurnOver() {
- return turnOver;
- }
- /**
- * Sets the turn over.
- *
- * @param turnOver
- * the new turn over
- */
- public void setTurnOver(double turnOver) {
- this.turnOver = turnOver;
- }
- }
- Organisation org = getPopulatedBean(); //Get the bean
- ByteArrayOutputStream out = null;
- try {
- JAXBContext jctx = JAXBContext.newInstance(Organisation.class);
- Marshaller marshaller = jctx.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
- out = new ByteArrayOutputStream();
- marshaller.marshal(org, out);
- String contents = new String(out.toByteArray());
- System.out.println("---------------Generated XML------------\n"
- +
- contents);
- } catch (JAXBException e) {
- System.out.println("JAXB Exception thrown ...");
- e.printStackTrace();
- } catch (Exception ex) {
- System.out.println("UnExpected Error ...");
- ex.printStackTrace();
- } finally {
- try {
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
Java Class to XSD
This topic seems interesting; how to generate an XML schema directly from Java classes. JAXB also provides a tool called "schemagen" to generate a XML schema in the form of a XSD file. "Schemage" is a part of JDK. If you have installed the JDK and set JAVA_HOME properly then you can type schemagen in the command prompt with the help command. It is always a recommended approach to use the Apache ANT script to generate a XSD file. Schemagen can generate a XSD file if your Java classes are provided with JAXB annotations. If you do not provide JAXB annotations then you will still be able to generate a XSD file. If you do not provide JAXB annotations then it will decide the XML element its own way. Let us see a brief code snippet for the ANT script to generate a XSD file.
- <target name="generate.schema" depends="compile">
- <exec executable="schemagen">
- <arg line="${class.name}"/>
- <arg line="-d ${schema.dir}"/>
- <arg line="-cp ${lib.dir}/org.jar"/>
- </exec>
- </target>
The preceding target generates an XSD file in a specified location with the name "schema1.xsd". Based upon the number of classes and namespaces provided in the JAXB annotation, it may generate more than one XSD file. This is the reason "schemagen" does not provide the facility to provide a name for the XSD file. In order to generate the XSD file properly, use the following procedure:
-
Create all the required Java Beans
-
Compile all the Java Beans
-
Create a JAR file out of the compiled classes
-
Use the required command for the "Schemagen" and provide the name of the JAR file as the path.
Instead of doing it manually, here I have done it using an ANT script that is very easy.
XML to XSD
XML to XSD conversion has been possible using any commercial tool available in the market. But there was no Java API that directly converts an XML document into an XSD file. There is an API called "trang" that helps to convert XML to XSD. It is free and open source. You can also use an ANT script to generate the XSD file. Let us see the ANT script code snippet below.
<exec command="java -jar ${lib.dir}/trang/trang.jar ${xml.dir}/org.xml ${xsd.dir}/org.xsd"/>
XML to DTD
In this case also, you can generate a DTD file using the "trang" API. I provide the following ANT code snippet to do that.
<exec command="java -jar ${lib.dir}/trang/trang.jar ${xml.dir}/org.xml ${dtd.dir}/org.dtd"/>
XSD to Java Classes
If you have an XSD file and if you are a Java developer then using the Jaxb API you can generate Java classes that you can use to generate the XML file. JAXB provides the "XJC" compiler to compile an XSD file into Java classes. From JDK 6 onwards, the "XJC" compiler is provided with JAXB. It provides a command-line utility and also an ANT script to generate classes. The generation of XML documents from the JAXB generated classes is called "Marshalling" and from XML to a Java object is called "UnMarshalling". Let us consider a typical XSD file as in the following:

Comments
Join the conversation! Your thoughts help the community grow.