Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Java生成UTF-8编码的XML_Java_Xml_Encoding - Fatal编程技术网

用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");