根据XStream的FAQ,它的默认解析器不保留UTF-8文档编码,必须提供自己的编码器。如何做到这一点?
谢谢!
答案 0 :(得分:35)
使用UTF-8编码创建一个Writer。将Writer作为参数传递给XStream的toXML方法。
XStream xstream = new xStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(outputStream, "UTF-8");
xStream.toXML(object, writer);
String xml = outputStream.toString("UTF-8");
您也可以使用该Writer包含XML声明。
writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
xStream.toXML(object, writer);
答案 1 :(得分:13)
另一种解决方案是通过驱动程序以正确的编码启动XStream对象。使用DomDriver,这看起来像:
XStream xstream = new XStream(new DomDriver("UTF-8"));
(默认)PrettyPrintWriter将由具有正确编码的输出流包装。 你无法以这种方式添加UTF-8标题......
答案 2 :(得分:3)
使用当前版本的XStream,@ Jeromy的示例如下所示:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8");
HierarchicalStreamWriter xmlWriter = new PrettyPrintWriter(writer);
xstream.marshal(object, xmlWriter);
return new String(stream.toByteArray(), "UTF-8");