How to create XSD from XML using Java Application


In this tutorial I am going to explain how to create or generate a XSD from the XML. I will use two different steps to create or generate a XSD from XML.

Using xsd-gen-0.2.0-jar-with-dependencies.jar:

To done this, first we need to have this “xsd-gen-VERSION-jar-with-dependencies.jar” jar file. In this example I am using the xsd-gen-0.2.0-jar-with-dependencies.jar version of the jar file.
Here is the sample XML file:

<?xml version="1.0"?>
<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>

The application to create / generate the XSD from XML:

package com.codesuggestions.xml;

import java.io.File;

import org.wiztools.xsdgen.XsdGen;

public class XmlSchemaGen {
 public static void main(String[] args) throws Exception{
  File file = new File("src/com/codesuggestions/xml/note.xml");
  new XsdGen().parse(file).write(System.out);
 }
}

In the example above it prints the output to the console, if you want to convert the output to string, you have to use the following code to converts the XSD document object to string object.

public class XmlSchemaGen {
 public static void main(String[] args) throws Exception{
        File file = new File("src/com/codesuggestions/xml/note.xml");
        String xsd = new XsdGen().parse(file).toString());
               System.out.println(xsd);
 }
}

Using the toString() method, the output is not in the formatted, if you want to convert the XSD string to formatted, use the following method to convert the XSD string formatted.

public static String formatXSD(String xsdString) {
 try {

  Source xmlInput = new StreamSource(new StringReader(xsdString));
  StringWriter stringWriter = new StringWriter();
  StreamResult xmlOutput = new StreamResult(stringWriter);
  TransformerFactory transformerFactory = TransformerFactory.newInstance();
  transformerFactory.setAttribute("indent-number", 2);
  Transformer transformer = transformerFactory.newTransformer();
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  transformer.transform(xmlInput, xmlOutput);

  return xmlOutput.getWriter().toString();
 } catch (Exception e) {
  throw new RuntimeException(e);
 }
}

If you run the above application you will get the following output:

<?xml version="1.0" encoding="UTF-8"?><xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="note">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="to" minOccurs="0" maxOccurs="1" type="xsd:normalizedString"/>
        <xsd:element name="from" minOccurs="0" maxOccurs="1" type="xsd:normalizedString"/>
        <xsd:element name="heading" minOccurs="0" maxOccurs="1" type="xsd:normalizedString"/>
        <xsd:element name="body" minOccurs="0" maxOccurs="1" type="xsd:string"/>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

Note:


In the jar file, the XsdGen constructors are default package access specifies, so you can not create the instance of this class outside of the package, you need to modify the source code of XsdGen constructors to public access specifies to create the instance of this class. You will find the source code of the XsdGen class in the following location: "http://xsd-gen.googlecode.com/svn/trunk/“. Extract the jar and copy the class which generated with the above changes and create the jar file back, or create a package with the same package structure as XsdGen class in your application package structure.

Using xbean-2.2.0.jar:

Xbeans is the Apache library, using this we can generate the XSD from XML. The XML can be String, File and InputStream.

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
 
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;
import org.apache.xmlbeans.impl.inst2xsd.Inst2Xsd;
import org.apache.xmlbeans.impl.inst2xsd.Inst2XsdOptions;
import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument;
 
public class XsdGen {
    public static void main(String[] args) {
        try {
            XsdGen xmlBeans = new XsdGen();
            SchemaDocument schemaDocument = xmlBeans.generateSchema(new File("src/com/codesuggestions/xml/note.xml"));
 
            StringWriter writer = new StringWriter();
            schemaDocument.save(writer, new XmlOptions().setSavePrettyPrint());
            writer.close();
 
            String xmlText = writer.toString();
            System.out.println(xmlText);
 
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public SchemaDocument generateSchema(File inputFile) throws XmlException, IOException {
        return generateSchema(inputFile, XMLSchemaDesign.VENETIAN_BLIND);
    }
 
    public SchemaDocument generateSchema(File inputFile, XMLSchemaDesign design) throws XmlException, IOException {
        // Only 1 instance is required for now
        XmlObject[] xmlInstances = new XmlObject[1];
        xmlInstances[0] = XmlObject.Factory.parse(inputFile);
 
        return inst2xsd(xmlInstances, design);
    }
 
    public SchemaDocument generateSchema(InputStream is, XMLSchemaDesign design) throws XmlException, IOException {
        // Only 1 instance is required for now
        XmlObject[] xmlInstances = new XmlObject[1];
        xmlInstances[0] = XmlObject.Factory.parse(is);
 
        return inst2xsd(xmlInstances, design);
    }
 
    public SchemaDocument generateSchema(String input) throws XmlException, IOException {
        return generateSchema(input, XMLSchemaDesign.VENETIAN_BLIND);
    }
 
    public SchemaDocument generateSchema(String input, XMLSchemaDesign design) throws XmlException, IOException {
        // Only 1 instance is required for now
        XmlObject[] xmlInstances = new XmlObject[1];
        xmlInstances[0] = XmlObject.Factory.parse(input);
 
        return inst2xsd(xmlInstances, design);
    }
 
    private SchemaDocument inst2xsd(XmlObject[] xmlInstances, XMLSchemaDesign design) throws IOException {
        Inst2XsdOptions inst2XsdOptions = new Inst2XsdOptions();
        if (design == null || design == XMLSchemaDesign.VENETIAN_BLIND) {
            inst2XsdOptions.setDesign(Inst2XsdOptions.DESIGN_VENETIAN_BLIND);
        } else if (design == XMLSchemaDesign.RUSSIAN_DOLL) {
            inst2XsdOptions.setDesign(Inst2XsdOptions.DESIGN_RUSSIAN_DOLL);
        } else if (design == XMLSchemaDesign.SALAMI_SLICE) {
            inst2XsdOptions.setDesign(Inst2XsdOptions.DESIGN_SALAMI_SLICE);
        }
 
        SchemaDocument[] schemaDocuments = Inst2Xsd.inst2xsd(xmlInstances, inst2XsdOptions);
        if (schemaDocuments != null && schemaDocuments.length > 0) {
            return schemaDocuments[0];
        }
 
        return null;
    }
}

Happy Coding...

No comments

Powered by Blogger.