Create a DTD from an Instance

If you need a DTD in a hurry, create it from an XML instance using Trang, Relaxer, DTDGenerator, or xmlspy.

Several free Java tools are available that can generate a DTD based on an XML instance or instances. James Clark’s Trang (http://www.thaiopensource.com/relaxng/trang.html) can, among other things, convert an XML document to a DTD, as can Relaxer (http://www.relaxer.org). Michael Kay’s DTDGenerator (http://saxon.sourceforge.net/dtdgen.html), once part of the Saxon project, consists of a single Java class that is dedicated to XML-to-DTD conversion. This hack walks you through the steps to generate a DTD from a simple instance using each of these tools.

Trang

You can download the current Trang JAR (trang.jar) from http://www.thaiopensource.com/download/, then place the JAR in the working directory. The Trang archive comes with a manual (trang-manual.html) that provides details on how to use Trang. I will cover only what is needed to create a DTD in this section. (If you need help with Java, refer to [Hack #10] .)

To create a DTD from time.xml, run this command:

java -jar trang.jar -I xml -O dtd time.xml generated.dtd

The -I switch indicates the type of input (XML), and -O indicates the type of output (DTD). time.xml is the input file and generated.dtd is the output file. You could simplify this command by skipping the -I and -O options, which will produce the same result:

java -jar trang.jar time.xml generated.dtd

The file generated.dtd looks like ...

Get XML Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.