XML字符编码

时间:2012-02-17 11:16:33

标签: java xml character-encoding

我正在基于这样的字符串生成XML:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

DocumentBuilder builder;
try {
    builder = factory.newDocumentBuilder();

    // Use String reader  
    Document document = builder.parse(new InputSource(new StringReader(txt)));

    TransformerFactory tranFactory = TransformerFactory.newInstance();
    Transformer aTransformer = tranFactory.newTransformer();
    Source src = new DOMSource(document);
    Result dest = new StreamResult(new File("C:\\Users\\root\\Desktop\\xmlFileName.xml"));
    aTransformer.transform(src, dest);
} catch (Exception e) {
    // TODO Auto-generated catch block  
    e.printStackTrace();
}

它会生成文件,但我遇到了字符问题。

例如,生成的XML的这一行:

<msg_detalhe>NÃ&#131;£o Ã&#131;© permitida a presenÃ&#131;§a de caracteres</msg_detalhe>

应该是:

<msg_detalhe>Não é permitida a presença de caracteres</msg_detalhe>

2 个答案:

答案 0 :(得分:1)

XML内容中的

使用CDATA ...

<![CDATA[content]]>

答案 1 :(得分:1)

尝试在运行程序时设置系统属性:-Dfile.encoding=UTF-8