问题描述
假设此输入XML
<?xml version="1.0" encoding="UTF-16"?>
<test></test>
编写以下代码:
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();
输出此XML:
<?xml version="1.0" encoding="UTF-8"?>
<test></test>
(声明的UTF- 16 编码转换为默认UTF - 8 )
(the declared encoding of UTF-16 is converted to the default UTF-8)
我知道我可以明确要求输入UTF-16。
I know I can explicitly ask for UTF-16 output
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-16");
但问题是,如何自动进行输出编码 >与输入相同
But the question is, how to make the output encoding automatically be the same as the input?
推荐答案
要做到这一点,比 StreamSource
。例如,需要一个 XMLStreamReader
,其中包含方法,告诉您输入文档使用的编码 - 您可以设置为输出enocding。
To do this, you'll have to use something more sophisticated than a StreamSource
. For example, a StAXSource
takes an XMLStreamReader
, which has the getCharacterEncodingScheme()
method that tells you which encoding the input document used - you can the set that as output enocding.
这篇关于如何在javax.xml.transform.Transformer.transform的输出中保留输入的声明编码? (例如,避免UTF-16更改为UTF-8)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!