Assuming this XML input
<?xml version="1.0" encoding="UTF-16"?>
<test></test>
Writing these lines of code:
StreamSource source = new StreamSource(new StringReader());
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?
source
share