xml转换编码问题
您好,我有一个简单的代码:
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 应该包含一个标头,其中编码设置为“UTF-16”,originla xml 为 UTF-8但我得到:(
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
独立属性似乎也是错误的) 变压器实例是:com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl (我认为这是默认的) 那么我想念这里什么呢?
Hi I have a simple code:
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()
that should trasnform an xml to UTF-16 encoding. Although internal representation of String in jvm already uses UTF-16 chars as far I know, but my expectations are that the result String should contain a header where the encoding is set to "UTF-16", originla xml where it was UTF-8 but I get:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
(also the standalone property seems to be wrong)
The transformer instance is: com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl
(what I think is a default)
So what I miss here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用明确声明 UTF-16 作为输出编码的编写器。尝试使用
OutputStreamWriter(OutputStream out, String charsetName)
来包装ByteArrayOutputStream
并查看是否有效。Use a writer where you explicitly declare UTF-16 as output encoding. Try
OutputStreamWriter(OutputStream out, String charsetName)
which should wrap aByteArrayOutputStream
and see if this works.我现在自己写了一个测试。有一个小的变化:
我有相同的结果但是该文件确实是 UTF-16 编码的,用十六进制编辑器检查。由于某些奇怪的原因,xml 声明没有更改。所以你的代码可以工作。
I have wrote a test on my own now. With one minor change:
I have the same results but the file is indeed UTF-16 encoded, checked with a hex editor. For some strange reason the xml declaration is not changed. So your code works.