如何使用XStream的框架编码UTF-8?(How do I encode UTF-8 using

2019-06-27 08:58发布

每XStream的的常见问题及其默认解析器不会保留UTF-8编码的文件,并且必须提供自己的编码器。 怎样才能做到这一点?

谢谢!

Answer 1:

创建UTF-8编码作家。 传作家作为参数传递给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");

您也可以使用该作家包括XML声明。

writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
xStream.toXML(object, writer);


Answer 2:

另一解决方案是,以启动XStream的对象与正确的编码,通过驱动器。 使用DomDriver这将是这样的:

XStream xstream = new XStream(new DomDriver("UTF-8"));

(默认)PrettyPrintWriter将通过与正确的编码的OutputStream缠绕。 你不能添加UTF-8头这样然而...



Answer 3:

与当前版本的XStream的,@杰罗米的例子是这样的:

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


文章来源: How do I encode UTF-8 using the XStream framework?