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

后端 未结 3 617
无人及你
无人及你 2020-12-13 15:53

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条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-13 16:25

    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("");
    xStream.toXML(object, writer);
    

提交回复
热议问题