Search code examples
javaxmliosaxstax

How to transform XMLStreamReader to XMLStreamWriter


Should be easy and obvious but I cant find a way - the XMLOutputFactory accepts anly OutputStream, Result or another Writer to generate a new XMLStreamWriter.

What I have at hand is an XMLStreamReader which has no methods for extracting a Result or an OutputStream.

If the solution would be easier using the Event API, that would be OK too.

Thank you


Solution

  • You could use a javax.xml.transform.Transformer to convert a StAXSource wrapping the reader to a StAXResult wrapping the writer.

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    StAXSource source = new StAXSource(xmlStreamReader);
    StAXResult result = new StAXResult(xmlStreamWriter);
    t.transform(source, result);
    

    Using the Event API you could also use the folloiwng: