根据 XStream 的常见问题解答,其默认解析器不保留 UTF-8 文档编码,并且必须提供自己的编码器。如何做到这一点?
谢谢!
使用 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);
另一种解决方案是通过驱动程序以正确的编码启动 XStream 对象。使用 DomDriver 这看起来像:
XStream xstream = new XStream(new DomDriver("UTF-8"));
(默认) PrettyPrintWriter 将由具有正确编码的输出流包装。但是,您不能以这种方式添加 UTF-8 标头...
With a current version of XStream, @Jeromy's example would look like this:
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");