views:

647

answers:

2

Hi

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..

+1  A: 

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.

Aaron Digulla
Thanks for the response. I am familiar with castor, so I am quite certain that it wouldn't fit my requirements. Perhaps JDom is the way to go.I am curious how the XML editors like the NetBeans plugin, XMLSpy, Oxygen etc are able to provide context sensitive prompting and look-aheads. I was hoping there is an open-source library/project that can do this out of box.
srini.venigalla
It's no problem to get the sources of the Netbeans or the Eclipse XML editors and have a look.
Aaron Digulla
+1  A: 

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.

Casey
Thanks, this is very close to what I was looking for.
srini.venigalla