用Java生成UTF-8编码的XML
这是我正在使用的代码用Java生成UTF-8编码的XML,java,xml,encoding,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.setAtt
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();
}
我如何做到这一点
我正在使用Java1.6-20
这类似于如果不希望XML编码为UTF-8,则不应该告诉转换器这样做 如果我没弄错你的问题
transformer.setOutputProperty(OutputKeys.ENCODING, "US-ASCII");
如果不希望XML编码为UTF-8,则不应告诉转换器这样做 如果我没弄错你的问题
transformer.setOutputProperty(OutputKeys.ENCODING, "US-ASCII");
应该生成所需的输出为什么需要字符引用而不是字符本身?既然你用的是UTF-8,你就不需要了,而且它携带着完全相同的信息。对不起,我没有把我的问题说清楚。我想逃跑。@Bouncyrabit:我明白了,但你为什么想逃跑?这两种形式完全相同,应该没有区别。为什么要字符引用而不是字符本身?既然你用的是UTF-8,你就不需要了,而且它携带着完全相同的信息。对不起,我没有把我的问题说清楚。我想逃跑。@Bouncyrabit:我明白了,但你为什么想逃跑?这两种形式完全相同,不应该有区别。
transformer.setOutputProperty(OutputKeys.ENCODING, "US-ASCII");