XMLStreamWriter#writeCharacters(.)
writeCharacters(.)方法用于转义字符,如&、<、>和".“(来自http://download.oracle.com/docs/cd/E17802_01/webservices/webservices/docs/2.0/tutorial/doc/StAX4.html)
但是,当我编写一些中文、日语字符时,输出的XML文件不是用"UTF-8“编码的,而是"GBK”或"Shift-JIS“。汉字、日文也是转义的,就像
汉语,英语,にほんご“--->”汉语,英语,にほんご
有什么要解决的吗?
public static void main(String[] args) throws Exception {
// GBK
System.out.println("JVM default charset = " + Charset.defaultCharset());
String s = "汉语, English, にほんご";
XMLOutputFactory output = XMLOutputFactory.newInstance();
output.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, false);
OutputStream out = new FileOutputStream("C:/aa.txt");
XMLStreamWriter writer = output.createXMLStreamWriter(out, "UTF-8");
// When output encoding is "UTF-8", result is something like:
// <?xml version='1.0' encoding='UTF-8'?><a>汉语, English, にほんご</a>
// When output encoding is "GBK", result is something like:
// <?xml version='1.0' encoding='GBK'?><a>汉语, English, にほんご</a>
writer.writeStartDocument();
writer.setDefaultNamespace("http://c");
writer.writeStartElement("http://c", "a");
writer.writeCharacters(s);
writer.writeEndElement();
writer.flush();
}
发布于 2010-12-06 23:36:42
当您创建作者时,用户XMLOutputFactory.createXMLEventWriter(stream, "UTF-8")
。我相信这能解决你的问题。
我没有使用这个特定的API,但是我使用了很多其他的API。例如,如果编码不支持字符,则由Properties.store()
方法自动进行转义。
https://stackoverflow.com/questions/4374260
复制