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

孤街浪徒 提交于 2019-11-28 18:25:31

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

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

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

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...

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");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!