Use Trang to Generate XSD from XML File

SHARE & COMMENT :

XML schema used for defining the restriction on XML data structure. It is adding the highly validated data structure and useful for defining the types for the data in XML files. In a normal practice, first a developer creates a XSD (schema) with validations or enforcement for the XML structure, later all the XML files created will use that XSD for validating the rules. In some scenarios, we have a valid XML file and we need to create a schema file for that XML structure. This tutorial explains how to create a XSD file using existing XML file. We will use a tool called trang for achieving this.

Download Trang

It is an open source API for working with XML files. One of the functionality it offers is to generate a XSD file using XML file. You can download the JAR file from here.

//java -jar <trang JAR file path> <XML file name> <XSD file name>
java -jar D:/trang.jar Sample.xml Sample.xsd

I have used the below sample XML and XSD files for this tutorial. If you have any questions, please write it in the comments section.

XML File

<?xml version="1.0" encoding="UTF-8"?>
<company>
	<branch>
		<employee id="001">
			<name>Name 1</name>
			<designation>Engineer</designation>
		</employee>
		<employee id="002">
			<name>Name 2</name>
			<designation>Engineer</designation>
		</employee>
	</branch>
</company>

Generate XML Schema

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:element name="company">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="branch"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="branch">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" ref="employee"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="employee">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="name"/>
        <xs:element ref="designation"/>
      </xs:sequence>
      <xs:attribute name="id" use="required" type="xs:integer"/>
    </xs:complexType>
  </xs:element>
  <xs:element name="name" type="xs:string"/>
  <xs:element name="designation" type="xs:NCName"/>
</xs:schema>

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better