【问题标题】:Troubles with XML encoding in JavaJava中XML编码的问题
【发布时间】:2015-06-11 16:37:52
【问题描述】:

XML 编码有问题。 当我在 localhost 上使用 cp1251 编码创建 XML 时,一切都很酷
但是当我在服务器上部署我的模块时,xml 文件有不正确的符号,如“ФайлПФД

 StringWriter writer = new StringWriter();
 StreamResult result = new StreamResult(writer);
 DOMSource source = new DOMSource(doc);

 transformer.setOutputProperty(OutputKeys.ENCODING, "cp1251");
 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
 transformer.transform(source, result);

 String attach = writer.toString();

我该如何解决?

【问题讨论】:

  • 为什么你不使用 unicode ?
  • 你是如何阅读这个文件的?
  • 我们自己生成的
  • 编写单元测试来验证 XML 文档可以被正确读取。如果没问题,那么问题出在读取文件的(服务器)代码上。
  • 萨达姆,我需要使用 Cp1251。根据客户要求

标签: java xml encoding cp1251


【解决方案1】:

我尝试读取UTF-8 编码的 XML Document,并尝试使用不同的编码对其进行转换,这根本没有效果(文档的现有编码是使用而不是我用输出属性指定的那个)。在内存中新建 Document(encoding 为 null)时,正确使用了 output 属性。

看起来在转换 XML Document 时,输出属性 OutputKeys.ENCODING 仅在 org.w3c.dom.Document 没有没有编码时使用。

解决方案
更改 XML 文档的编码,不要使用 Document 作为源,而是使用它的 根节点(文档元素)。

// use doc.getDocumentElement() instead of doc
DOMSource source = new DOMSource(doc.getDocumentElement());

像魅力一样工作。

源文件:

<?xml version="1.0" encoding="UTF-8"?>
<foo bla="Grüezi">
    Encoding test äöüÄÖÜ «Test»
</foo>

使用“cp1251”输出:

<?xml version="1.0" encoding="WINDOWS-1251"?><foo bla="Gr&#252;ezi">
    Encoding test &#228;&#246;&#252;&#196;&#214;&#220; «Test»
</foo>

【讨论】:

    【解决方案2】:

    A (String)Writer 不会受到输出编码的影响(仅受到使用的输入编码的影响),因为 Java 以 Unicode 维护所有文本。要么写入二进制,要么将字符串输出为 Cp1251。

    请注意,编码应该在&lt;?xml encoding="Windows-1251"&gt; 行中。而且我猜“Cp1251”更具体一点。

    所以错误可能在于字符串的写入;比如

    response.setCharacterEncoding("Windows-1251");
    response.write(attach);
    

    或者

    attach.getBytes("Windows-1251")
    

    【讨论】: