Validation using JAXB and Stax to marshal XML document
Question
I have created an XML schema (foo.xsd) and used xjc
to create my binding classes for JAXB. Let's say the root element is collection
and I am writing N document
objects, which are complex types.
Because I plan to write out large XML files, I am using Stax to write out the collection
root element, and JAXB to marshal document subtrees using Marshaller.marshal(JAXBElement, XMLEventWriter)
. This is the approach recommended by jaxb's unofficial user's guide.
My question is, how can I validate the XML while it's being marshalled? If I bind a schema to the JAXB marshaller (using Marshaller.setSchema()
), I get validation errors because I am only marshalling a subtree (it's complaining that it's not seeing the collection
root element"). I suppose what I really want to do is bind a schema to the Stax XMLEventWriter
or something like that.
Any comments on this overall approach would be helpful. Basically I want to be able to use JAXB
to marshal and unmarshal large XML documents without running out of memory, so if there's a better way to do this let me know.
Solution
Some Stax implementations seem to be able to validate output. See the following answer to a similar question: