How to save entered input encoding in javax.xml.transform.Transformer.transform output? (for example, so that UTF-16 does not switch to UTF-8)

Assuming this XML input

<?xml version="1.0" encoding="UTF-16"?>
<test></test>

Writing these lines of code:

StreamSource source = new StreamSource(new StringReader(/* the above XML*/));
StringWriter stringWriter = new StringWriter();
StreamResult streamResult = new StreamResult(stringWriter);
TransformerFactory.newInstance().newTransformer().transform(source, streamResult);
return stringWriter.getBuffer().toString();

The output for me of this XML is:

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

(declared encoding UTF- 16 is converted to UTF by default - 8 )

I know I can explicitly request UTF-16 output

transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-16");

But the question is how to make the output encoding automatically the same as the input?

+5
source share
4 answers

- , StreamSource. , StAXSource XMLStreamReader, getCharacterEncodingScheme(), , - enocding.

+3
+1

The XSLT processor does not actually know what the input encoding is (the XML parser does not say this because it does not need to be known). You can set the output encoding with xsl: output, but in order to make it the same as the input encoding, you will need to first find the input encoding, for example, by looking at the source file before parsing it.

+1
source

try the following:

// Create an XML Stream Reader
XMLStreamReader xmlSR = XMLInputFactory.newInstance()
        .createXMLStreamReader(new StringReader(/* the above XML*/));
// Wrap the XML Stream Reader in a StAXSource
StAXSource source = new StAXSource(xmlSR);
// Create a String Writer
StringWriter stringWriter = new StringWriter();
// Create a Stream Result
StreamResult streamResult = new StreamResult(stringWriter);
// Create a transformer
Transformer transformer = TransformerFactory.newInstance().newTransformer();
// Set STANDALONE based on the source stream
transformer.setOutputProperty(OutputKeys.STANDALONE,
        xmlSR.isStandalone() ? "yes" : "no");
// Set ENCODING based on the source stream
transformer.setOutputProperty(OutputKeys.ENCODING,
        xmlSR.getCharacterEncodingScheme());
// Set VERSION based on the source stream
transformer.setOutputProperty(OutputKeys.VERSION, xmlSR.getVersion());
// Transform the source stream to the out stream
transformer.transform(source, streamResult);
// Print the results
return stringWriter.getBuffer().toString();
+1
source

All Articles