O'Reilly logo

XML Hacks by Michael Fitzgerald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Generate Code from XML

Tools are readily available that can convert XML into Java code, which in turn can allow you to easily manipulate markup from code rather than by hand in an editor or with something like XSLT. This hack walks you through an XML-to-code conversion scenario, and shows you how you can use the code after producing it.

This hack will demonstrate one tool that can generate code from either XML documents or a schema. Relaxer (http://www.relaxer.org) is a free Java tool that, among many other things, can generate Java code from XML documents, RELAX NG schemas (http://www.relaxng.org), or Relax Core schemas (http://www.xml.gr.jp/relax/).

Using Relaxer to Generate Java

With Relaxer, you can generate Java source code from an XML document or from a RELAX NG schema. In this example, we’ll generate code based on the instance time.xml. Assuming that Relaxer is installed and ready to roll [Hack #37] , type this command while in the working directory where the book files were extracted:

relaxer -verbose -java -useJAXP time.xml

From this command, Relaxer produces the following five Java files—11,358 lines of code in a matter of seconds:

  • Time.java

  • Atomic.java

  • RStack.java

  • UJAXP.java

  • URelaxer.java

Time.java and Atomic.java are based on time.xml. These Java classes provide a set of constructors for creating objects based on this data model. For example, both Time.java and Atomic.java provide a default constructor (no arguments), another constructor that accepts a DOM document ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required