I'm trying to output a CDATA section in the result of XSLT using Xalan 2.7.1. I have applied this XSL to the XML in a tool and the result contains CDATA. In the method below, no CDATA is in the result and no exception is thrown. I feel like I'm missing something here.
test.xml
<?xml version="1.0" encoding="UTF-8"?>
<parentelem>
<childelem>Test text</childelem>
</parentelem>
test.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="UTF-8" cdata-section-elements="newchildelem" />
<xsl:template match="/">
<parentelem>
<newchildelem><xsl:value-of select="/parentelem/childelem" /></newchildelem>
</parentelem>
</xsl:template>
</xsl:stylesheet>
Transform.java
import java.io.FileReader;
import java.io.StringWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stax.StAXResult;
import javax.xml.transform.stax.StAXSource;
public class Transform {
public static void main (String[] args){
try {
XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(
new FileReader("test.xml"));
XMLStreamReader xslReader = XMLInputFactory.newInstance().createXMLStreamReader(
new FileReader("test.xsl"));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Source xslSource = new StAXSource(xslReader);
Source xmlSource = new StAXSource(xmlReader);
Transformer transf = transformerFactory.newTransformer(xslSource);
StringWriter xmlString = new StringWriter();
XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(
xmlString);
Result transformedXml = new StAXResult(xmlWriter);
transf.transform(xmlSource, transformedXml);
xmlWriter.flush();
System.out.println(xmlString.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
console output
<?xml version="1.0" encoding="UTF-8"?><parentelem><newchildelem>Test text</newchildelem></parentelem>