在Java中使用XML编码的麻烦

时间:2015-04-07 06:51:12

标签: java xml encoding cp1251

我遇到了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();

我如何解决它?

2 个答案:

答案 0 :(得分:3)

我尝试读取Document编码的UTF-8,并尝试使用不同的编码对其进行转换,该编码根本没有效果(现有编码)使用该文档而不是我使用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>

答案 1 :(得分:0)

A(String)Writer不受输出编码的影响(仅来自使用的输入编码),因为Java维护Unicode中的所有文本。写入二进制文件,或将字符串输出为Cp1251。

请注意,编码应位于<?xml encoding="Windows-1251">行。我想&#34; Cp1251&#34;是特定于java的。

所以错误可能在于写字符串;例如

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

或者

attach.getBytes("Windows-1251")
相关问题