Generate XSD from XML

There are several tools out there to create (or to infer) an XSD schema from XML document. I liked trang command line tool the most. Found it first when reading about Spring web services in Spring in Action book (very good book btw).

Here are four simple steps how to create XSD from XML* using trang:

Step 1. Get trang

Download trang.zip from here (at the moment of writing “trang-20030619.zip”)

Step 2. Extract it

Use “unzip trang-version.zip”, or just winzip/winrar/7z etc.. if on windows

Step 3. Make an alias

This step is optional, but makes it extremely easy to run the tool with a single command. Make an alias to the “trang.jar” by (in my case Ubuntu/Linux) editing “~/.bashrc” and adding the following:

# execute trang.jar (create XSD from XMLs)
alias xml2xsd='java -jar ~/soft/utils/trang/trang-20030619/trang.jar'

above “~/soft/utils/trang” is the directory where “trang” was unzipped to.

Step 4. Create XSD from XML

Let’s look at the XML file we need an XSD for:

$ ls -l
total 4
-rw-r--r-- 1 user group 357 2008-05-28 15:38 holiday-request.xml
 
$ cat holiday-request.xml
<?xml version="1.0" encoding="UTF-8"?>
<holidayRequest xmlns="http://mycompany.com/hr/schemas">
    <holiday>
        <startDate>2006-07-03</startDate>
        <endDate>2006-07-07</endDate>
    </holiday>
    <employee>
        <number>42</number>
        <firstName>Ultimate</firstName>
        <lastName>Answer</lastName>
    </employee>
</holidayRequest>

now run the tool against it:

$ xml2xsd holiday-request.xml hr.xsd
$ cat hr.xsd
<?xml version=”1.0″ encoding=”UTF-8″?>
<xs:schema xmlns:xs=”http://www.w3.org/2001/XMLSchema” elementFormDefault=”qualified” targetNamespace=”http://mycompany.com/hr/schemas” xmlns:schemas=”http://mycompany.com/hr/schemas”>
  <xs:element name=”HolidayRequest”>
    <xs:complexType>
      <xs:sequence>
        <xs:element ref=”schemas:Holiday”/>
        <xs:element ref=”schemas:Employee”/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name=”Holiday”>
    <xs:complexType>
      <xs:sequence>
        <xs:element ref=”schemas:StartDate”/>
        <xs:element ref=”schemas:EndDate”/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name=”StartDate” type=”xs:NMTOKEN”/>
  <xs:element name=”EndDate” type=”xs:NMTOKEN”/>
  <xs:element name=”Employee”>
    <xs:complexType>
      <xs:sequence>
        <xs:element ref=”schemas:Number”/>
        <xs:element ref=”schemas:FirstName”/>
        <xs:element ref=”schemas:LastName”/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name=”Number” type=”xs:integer”/>
  <xs:element name=”FirstName” type=”xs:NCName”/>
  <xs:element name=”LastName” type=”xs:NCName”/>
</xs:schema>

done!

$

* – NOTE: “trang” can create an XSD from multiple XML documents, not just one.


List of other tools to use as an alternative to trang:

XSD away, Good Luck!

80 comments

  1. stevie lang

    exactly what I was looking for – thanks man!

  2. excellent!

    I think you got pretty much all those XML -> XSD tools in one place – very helpful.

    thank you very much!

  3. “trang” is definitely good and simple to use. There is a windows tool xsd.exe
    that can do that as well (if there is a need)

    good article – thank you!

  4. trang is awesome. I had not heard about it before. I have used Oxygen before definitely the bst XML editor in the market.

    Although I used Oxygen a couple of years ago and Altova used to suck back then. I have heard Altova is much better now.

  5. How to insert data into SQL Server 2005 using Adobe Live Cycle PDF Form….Please help me out i am new to Adobe Live Cycle…Please Post me the Code…

  6. Suresh,

    I am not sure why you have posted you question here to the “Generate XSD from XML” article, and I have never worked with LiveCycle’s generated PDF Forms, but:

    According to the LiveCycle Designer documentation:

    “Designer can directly link a form to a database without scripting, as well as integrating into an enterprise data management system.”

    So I would suggest to browse around configuration that is available to see how you can link your form to the DB.

    For MS SQL Server specifically, you may need to use the specific driver to enable the datasource to connect to MS SQL Server successfully.

    – Toly

  7. Is there anything available similar to this tool but reverse way , i.e. Generate XML from XSD?

  8. @Manisha

    Firstly, you can try a couple of Eclipse’s way:

    Generating XML files from XML schemas: http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.wst.xmleditor.doc.user/topics/tcrexxsd.html

    Creating XML files WebTools Tutorial: http://www.eclipse.org/webtools/community/tutorials/XMLWizards/XMLWizards.html

    Secondly, you may want to take a look at XMLSpear (free tool) http://www.donkeydevelopment.com/, one of the feature of which is to “Generation of complete XML documents from schema”

    Finally, XMPSpy, and other XML editors can do the same thing.

    Let me know if you need more info,

    – Toly

  9. Thanks, Toly for your response.

    These are all seems to be Windows based tools, I am looking for something which will work on unix, basically commandline tool. I tried Sun XML instance generator, but somehow it does not generate proper XML.

  10. XMLSpear is a java program and it has a XMLSpear.sh script for staring the application on Unix based systems,

    -DD

  11. @ DD,

    Thanks DD!

  12. Adding to the list of tools is now the OASIS CAM processor toolkit. This ingests XSD schema into a CAM template – and then allows you to create realistic XML test samples using content hinting and customized content models. Realistic test cases is the next level above random content generation. See http://wiki.oasis-open.org/cam for more information and a tutorial.

  13. Just realized I can also save sometime with the direct link to the XML test generator page:
    http://wiki.oasis-open.org/cam/Generating_XML_test_examples_from_XSD

  14. Right on man this was EXACTLY what I was looking for. Thanks for putting together a list of resources and a perfect little walk through!

  15. Really you explained in very easy way. I did on the same on window and it woked without any problem. I used this command to create XSD file
    C:\>java -jar c:\jar\trang-20030619\trang-2
    0030619\trang.jar holiday-request.xml hr.xsd

    Thanks. :)

  16. This message is for Suresh, although I know it’s late. I’ve worked alot with LiveCycle, and if you’re trying to get data into and out of a database, the best way we have found to do that is via web services. You can use any web services, .Net, Java, etc and link the parameters from the web service to your form. You can also create an ODBC connection directly to the database, although I recommend using web services. If you use ODBC you’re going to have to somehow get the driver installed on client machines. Web services make sure that you don’t have to touch the machine opening your form. Hope this wasn’t too late for ya pal. BTW trang is very, very cool. I use it for most of my xml to xsd conversions now. Visual Studio also has a pretty good one, but sometimes adds stuff that LiveCycle doesn’t like. Trang seems to get it right everytime…

    Thanks for the post!!!

  17. Thanks you, I need a tools like this!!!

  18. Extremely helpful, thanks for sharing.

    One basic query- which is more apt, xsd or dtd?

  19. @ShyGuy78,

    What do you mean by APT?

    Here are some differences between XSD and DTD:

    DTD’s are not namespace aware.

    DTD’s have #define, #include, and #ifdef — or, less C-oriented, the ability to define shorthand abbreviations, external content, and some conditional parsing.

    A DTD describes the entire XML document; a schema can define portions.

    XSD has a type system.

    XSD has a much richer language for describing what element or attribute content “looks like.” This is related to the type system.

    You can put a DTD inline into an XML document, you cannot do this with XSD. This means DTD’s are more secure (you only have to protect one bytestream — the xml/dtd — and not multiple).

    The official definition of “valid XML” requires a DTD. Since this may be impractical, if not impossible, you often have to settle for schema-valid, which is not quite the same.

    In terms of validation functionality, XSD can define all the constraints that a DTD can define, and many more. To take a simple example, XSD can say that a particular attribute must be a valid date, or a number, or a list of URIs, or a string that is exactly 8 characters long. To take another example, XSD can define much richer constraints on uniqueness of values within a document.

    – Toly

  20. Very interesting post! Thanks!

    I also would like to recommend a new tool that can generate xsd from xml called Rinzo Xml. http://sourceforge.net/projects/editorxml/

  21. @MetalFan – Thanks for sharing – will give rinzo a try :)

  22. hi am a testing engg..i would like to know that..all the binded fields are generating some values in the preview of livecycle Designer..can anybody know that,from where that values are coming to the forms?

  23. Great tool.
    Now it I wanna embed this XSD generation logic into my code, is there any Trang API to use, rather than the command line?

  24. Thank you very much, this is exactly what I was looking for!

  25. Same than reto, exactly what I was looking for, thanks for tutorial btw :)

  26. This is really great. Thanks a lot. Really helpful. Liked tranche.

  27. That made my life a lot easier, thanks to you and the developer(s) of Trang

  28. Jose Luis Perez

    Great tool thanks

  29. When I try to generate xsd from java object. It is generating XSD file
    finely. But the problem is it isgenerating XSD file elements in
    alphabetical order.
    can u please sujest me how can we do that one. I tried with annotation
    in java object but I am not getting the desired output(order which is
    given in the java objects) Do we need to change any properties in
    Netbeans IDE? Please suggest.

  30. great tool, found it really useful.

  31. this is what I  was looking for, thanks

  32. Your toy example works fine, but when I attempt to infer an XSD from a 500 line XML file, I get the following exception:

    Exception in thread “main” java.util.ConcurrentModificationException
    at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
    at java.util.AbstractList$Itr.next(AbstractList.java:343)
    at com.thaiopensource.relaxng.input.xml.Inferrer.(Unknown Source)
    at com.thaiopensource.relaxng.input.xml.Inferrer.infer(Unknown Source)
    at com.thaiopensource.relaxng.input.xml.XmlInputFormat.load(Unknown Source)
    at com.thaiopensource.relaxng.input.AbstractMultiInputFormat.load(Unknown Source)
    at com.thaiopensource.relaxng.translate.Driver.doMain(Unknown Source)
    at com.thaiopensource.relaxng.translate.Driver.main(Unknown Source)

  33. OK I found what caused it. I used the same name for a tag in two different parts of the XML document to mean two different things. Still, it would be nice if I got a more helpful error message than that.

  34. OK sorry last thing. The newest version of trang fixes this issue (http://code.google.com/p/jing-trang/issues/detail?id=111) . Download it at http://code.google.com/p/jing-trang/downloads/list . Confirmed working on trang-20091111

    Thanks for this blog post, I wouldn’t have found out about this awesome tool otherwise.

  35. Cool, Thanks for your sharing.

  36. Thanks for this, really helpful

  37. E:\Trang_jar>java -jar E:\Trang_jar\trang.jar demo.xml hr.xsd
    Exception in thread “main” java.lang.NoClassDefFoundError: org/xml/sax/SAXException

  38. @ Manisha
    Try this XML editor. It works in Windows and Unix

  39. Thank you very much for your little yet helpful tool.
    Greetings, mate:)

  40. exactly what I was looking for

  41. Very useful tool and very easy to use. Job done in the first attempt. Thank you.

  42. Thank you, thats all what I need

  43. Absolutaly wonderfull…thnx sir..

  44. I have found liquid xml editor tool quite handy for infering xml schemas, has anybody else heard of this software?

  45. pretty old blog post… nevertheless exactly what i need at the meoment. thanks. :)

  46. how I will to generate java objectfrom xsd. i need API on this trang.jar please guide me

  47. thank you so much!!

  48. thanks for the cool tutorial, btw I struggled with trang and tried xml bean as listed above and liquid xml editor ( http://www.liquid-technologies.com/xml-editor.aspx ), anybody else find liquid xml any good?

  49. spot on…

tell me something...
  1. (required)
  2. (valid email - optional)
  3. Captcha
  4. (required)