Xml – Programmatically creating an XML Document using an XSD


I need to create XML documents using built-in java org.w3c.dom or jdom packages conforming to a set of XSD files. The XSD files are similar but not the same. In essence, I need to create the XML file as per the XSD given to me dynamically.

What is the best way to do it. I have checked the Validator package, it does not have any features like look-ahead or iterators for the possible elements at a given context node.

Ideally, I am looking at a SAX kind of architecture where I implement an element when I am asked to provide in a context-free manner. The engine should assemble and give me the dom tree at the end.

Is this wheel already been invented?


Best Solution

org.w3c.dom has no support for XML Schemas. For JDom, you can use schemas to validate a document, but there is no support to build documents.

You have two options:

  1. Use JDom to read the schema, analyze it and produce a document according to this XML document (a schema is always a valid XML document, too).

  2. You can use an XML mapper like Castor. Castor can read a Schema and produce a set of Java classes that allow you to produce documents which match said schema.

The latter approach might not work so well in your case since Castor will generate different Java classes for similar XSD structures unless they are defined in the same document, so you can't easily reuse the common code. The workaround is to let Castor generate the code and then write a script or similar to copy/merge the common parts of the XSDs into the same Java package.