I have a program that writes some XML files like this:
Path path = Paths.get(new URI("file://" + this.destination));
StringBuilder sb = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Responses>\n");
// Get a bunch of data from a remote web service
sb.append("</Responses>");
Files.write(path, sb.toString().getBytes(Charset.forName("UTF-8")), StandardOpenOption.CREATE);
The code that reads the files looks like this:
import javax.xml.transform.stream.StreamSource;
// ...
// Load XSLT
Source source = new StreamSource(this.getClass().getClassLoader().getResourceAsStream("my_transform.xsl"));
Transformer transformer = factory.newTransformer(source);
// set parameter
transformer.setParameter("db", dbName);
// Get input file
Source xmlSource = new StreamSource(this.pathToFile.toFile());
// Execute transform
transformer.transform(xmlSource, outputTarget);
The transform itself is very simple:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" indent="no" encoding="utf-8"
        media-type="text/plain" />
    <xsl:strip-space elements="*" />
    <xsl:param name="db" />
    <xsl:template match="/ELEMENT1/ELEMENT2/ELEMENT3/data[@dbname=$db]">
        <xsl:value-of select="../../@id" />
        <xsl:text>	</xsl:text>
        <xsl:value-of select="./@primary_id" />
        <xsl:text>
</xsl:text>
    </xsl:template>
</xsl:stylesheet>
The XML files are large, but they look OK, here's the first few lines of one:
<?xml version="1.0" encoding="utf-8"?>
<Responses>
<Response id="ID0000123">
  <opt>
    <data  primary_id="ID0000123-01" version="0">
When my code attempts to execute the transform, it throws an exception:
ERROR:  'Content is not allowed in prolog.'
ERROR:  'com.sun.org.apache.xml.internal.utils.WrappedRuntimeException: Content is not allowed in prolog.'
javax.xml.transform.TransformerException: javax.xml.transform.TransformerException: com.sun.org.apache.xml.internal.utils.WrappedRuntimeException: Content is not allowed in prolog.
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:749)
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:351)
...
I'm not sure where this is coming in from. The last time this happened to me  it was a character set mismatch, but in this case I'm writing the file as UTF-8 and loading it with StreamSource which I thought would load the character set correctly, so I'm not sure why the transform is failing.
 
     
    