Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8238183

SAX2StAXStreamWriter cannot deal with comments prior to the root element

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P4 P4
    • 15
    • 11.0.5
    • xml

      A DESCRIPTION OF THE PROBLEM :
      If I try to transform from a StreamSource of an XML file having a comment between XML declaration and xml root element to a StaxResult (constructed from a XMLStreamWriter) I run into a
      javax.xml.transform.TransformerException: org.xml.sax.SAXException: Can not output XML declaration, after other output has already been done.


      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      See java code

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      The transformation does not throw an exception
      ACTUAL -
      The transformation throws a javax.xml.transform.TransformerException

      ---------- BEGIN SOURCE ----------
      package org.apache.jackrabbit.vault.fs.io;

      import java.io.ByteArrayOutputStream;
      import java.io.IOException;
      import java.io.OutputStream;
      import java.io.Reader;
      import java.io.StringReader;

      import javax.xml.stream.XMLOutputFactory;
      import javax.xml.stream.XMLStreamException;
      import javax.xml.stream.XMLStreamWriter;
      import javax.xml.transform.Transformer;
      import javax.xml.transform.TransformerException;
      import javax.xml.transform.TransformerFactory;
      import javax.xml.transform.stax.StAXResult;
      import javax.xml.transform.stream.StreamSource;

      public class Main {

          public static void main(String[] args) throws IOException, XMLStreamException, TransformerException {
              String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                      "<!--comment-->\n" +
                      "<root />\n";
              try (Reader reader = new StringReader(xml);
                   OutputStream out = new ByteArrayOutputStream()) {
                       XMLOutputFactory factory = XMLOutputFactory.newFactory();
                       XMLStreamWriter writer = factory.createXMLStreamWriter(out);
                       TransformerFactory tf = TransformerFactory.newInstance();
                       Transformer t = tf.newTransformer();
                       StreamSource source = new StreamSource(reader);
                       StAXResult result = new StAXResult(writer);
                       t.transform(source, result);
                   }
          }
      }
      ---------- END SOURCE ----------

      FREQUENCY : always


            joehw Joe Wang
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: