The following example illustrates how to use the Java XML API to build a streaming XML pipeline that:
- reads an input stream (
- validates it against an XML schema (
- transforms it using XSLT (
- validates the result against another schema (
- applies another XSLT transformation (
- validates that result against yet another schema (
- writes the result to a stream (
Here is the code:
SchemaFactory schemas = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema1 = schemas.newSchema(new StreamSource(xsd1)); Schema schema2 = schemas.newSchema(new StreamSource(xsd2)); Schema schema3 = schemas.newSchema(new StreamSource(xsd3)); ValidatorHandler validator1 = schema1.newValidatorHandler(); ValidatorHandler validator2 = schema2.newValidatorHandler(); ValidatorHandler validator3 = schema3.newValidatorHandler(); SAXTransformerFactory transformers = SAXTransformerFactory.class.cast(TransformerFactory.newInstance()); Templates template1 = transformers.newTemplates(new StreamSource(xslt1)); Templates template2 = transformers.newTemplates(new StreamSource(xslt2)); Transformer transformer0 = transformers.newTransformer(); TransformerHandler transformer1 = transformers.newTransformerHandler(template1); TransformerHandler transformer2 = transformers.newTransformerHandler(template2); TransformerHandler transformer3 = transformers.newTransformerHandler(); validator1.setContentHandler(transformer1); transformer1.setResult(new SAXResult(validator2)); validator2.setContentHandler(transformer2); transformer2.setResult(new SAXResult(validator3)); validator3.setContentHandler(transformer3); transformer3.setResult(new StreamResult(output)); transformer0.transform(new StreamSource(input), new SAXResult(validator1));
This code does not introduce any intermediate DOM trees, string buffers or temporary files (of its own that is -- no warranties are offered for the parser or the XSD and XSLT processors). The key part of this solution is its use of transformer and validator SAX handlers. Also note the use of so-called identity transformers at the start and end of the pipeline. Strictly speaking, the solution could be shortened slightly by using the
validate method on a validator, but I present the code as is to emphasize the transformer's role as the "backbone" of the pipeline.
As far as I can tell, there is no StAX analog to this approach in Java 6. The transformation and validation APIs have not yet been updated to know about StAX input streams. The Javadoc for StAXResult makes a cryptic remark about how
Validator can accept a
Result as input, but I think that this is just awkward wording -- those classes show no evidence of living up to that remark.