xml 如何使用 XStream 框架对 UTF-8 进行编码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1211624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 12:40:01  来源:igfitidea点击:

How do I encode UTF-8 using the XStream framework?

xmlutf-8encodexstream

提问by Jeromy Evans

Per XStream's FAQ its default parser does not preserve UTF-8 document encoding, and one must provide their own encoder. How does one do this?

根据 XStream 的常见问题解答,其默认解析器不保留 UTF-8 文档编码,并且必须提供自己的编码器。如何做到这一点?

Thanks!

谢谢!

回答by Jeromy Evans

Create a Writer with UTF-8 encoding. Pass the Writer as an argument to XStream's toXML method.

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

You may also use that Writer to include the XML Declaration.

您还可以使用该 Writer 来包含 XML 声明。

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

回答by user117623

Another solution would be to initiate the XStream-object with correct encoding, through a driver. Using the DomDriver this would look like:

另一种解决方案是通过驱动程序以正确的编码启动 XStream 对象。使用 DomDriver 这看起来像:

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

The (default) PrettyPrintWriter will be wrapped by an outputstream with correct encoding. You could not add the UTF-8 header this way however...

(默认)PrettyPrintWriter 将由具有正确编码的输出流包装。但是,您无法以这种方式添加 UTF-8 标头...

回答by Urs Reupke

With a current version of XStream, @Jeromy's example would look like this:

使用当前版本的 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");