嗨,我有一个简单的代码:
InputSource is = new InputSource(new StringReader(xml))
Document d = documentBuilder.parse(is)
StringWriter result = new StringWriter()
DOMSource ds = new DOMSource(d)
Transformer t = TransformerFactory.newInstance().newTransformer()
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
t.setOutputProperty(OutputKeys.STANDALONE, "yes");
t.setOutputProperty(OutputKeys.ENCODING,"UTF-16")
t.transform(ds,new StreamResult(result))
return result.toString()
应该将 xml 转换为 UTF-16 编码。虽然据我所知,jvm 中 String 的内部表示已经使用 UTF-16 字符,但我的期望是结果 String 应该包含一个 header ,其中编码设置为“UTF-16”,originla xml 为 UTF-8但我得到:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
(独立属性似乎也是错误的) 变压器实例是:com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl (我认为这是默认的) 那么我在这里想念什么?
最佳答案
使用明确声明 UTF-16 作为输出编码的编写器。尝试 OutputStreamWriter(OutputStream out, String charsetName)
,它应该包装一个 ByteArrayOutputStream
并看看这是否有效。
关于java - xml转换编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6995733/