14

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?

Thanks!

3 Answers3

36

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);
Jeromy Evans
  • 494
  • 4
  • 6
13

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

user117623
  • 131
  • 1
  • 3
3

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");
Urs Reupke
  • 6,791
  • 3
  • 35
  • 49