srini.venigalla
srini.venigalla

Reputation: 5145

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?

Thanks..

Upvotes: 0

Views: 5304

Answers (2)

user147373
user147373

Reputation:

I am currently parsing an XSD and creating not an XML document off of parts of it, but something else. I found that XSOM was very useful. Have a look at this short little tutorial as it isn't obvious how to use it right off.

The library itself isn't hard to use once you get the hang of it and you can get any all information found in the XSD i.e. attributes, restrictions and elements which you can use to generate a XML file off of.

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328624

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.

Upvotes: 1

Related Questions