Search code examples
javaxmlxsltjaxbjaxb2

Exclude processing instruction from XSLT


I have a simple plain-text-generating XSLT that I am applying like this (using the reference implementation):

    StreamSource schemasource = new StreamSource(getClass().getResourceAsStream("source.xml"));
    StreamSource stylesource = new StreamSource(getClass().getResourceAsStream("transform.xslt"));
    Transformer transformer = TransformerFactory.newInstance().newTransformer(stylesource);

    StringWriter writer = new StringWriter();
    transformer.transform(schemasource, new StreamResult(domWriter));
    System.out.println("XML after transform:");
    System.out.println(writer.toString());

The "transform" call always inserts an processing instruction in the output. Is there any way to configure it not to do so?

(For example for a very simple node identity transform

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:template match="*">
        <xsl:copy/>
        <xsl:apply-templates/>
    </xsl:template>
</xsl:stylesheet>

when applied to

<hello/>

I get

<?xml version="1.0" encoding="UTF-8"?>
<hello/>

)

Many thanks, Andy


Solution

  • Strictly speaking the <?xml declaration is not a processing instruction. However, you should be able to use the xsl:output command here to specify that no xml declaration should be output:

    <xsl:output method="xml" omit-xml-declaration="yes"  indent="yes" />
    

    This should be placed as a direct child of the xsl:stylesheet element.