用Java生成UTF-8编码的XML

时间:2011-09-30 06:48:22

标签: java xml encoding

这是我正在使用的代码

try {
String str = "\uC3BC and \uC3B6 and <&> für";

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.newDocument();
Element root = doc.createElement("test");
root.setAttribute("attribute", str);
doc.appendChild(root);

DOMSource domSource = new DOMSource(doc);
// FileOutputStream out = new FileOutputStream("test.xml");
Writer out = new OutputStreamWriter(new FileOutputStream("test.xml"), "UTF8");

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(domSource, new StreamResult(out));

out.close();
} catch (Exception e) {
e.printStackTrace();
}

输出

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<test attribute="쎼 and 쎶 and &lt;&amp;&gt; für"/>

我希望它输出

attribute="&#xc3bc and &#xc3b6 ..."

我如何做到这一点?

我正在使用Java 1.6-20

这类似于Producing valid XML with Java and UTF-8 encoding

1 个答案:

答案 0 :(得分:6)

如果您不希望将XML编码为UTF-8,则不应告诉转换器这样做。

如果我理解你的问题

transformer.setOutputProperty(OutputKeys.ENCODING, "US-ASCII");

应该产生你想要的输出