带有特殊字符的Xstream

时间:2011-03-09 18:19:52

标签: java encoding utf-8 xstream

我正在使用XStream,但我对特殊字符á,é,í,ó,ú和ñ有问题。

我试过了:

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

(不工作)

我发现XStream does no character encoding by itself, it relies on the configuration of the underlying XML writer. By default it uses its own PrettyPrintWriter which writes into the default encoding of the current locale. To write UTF-8 you have to provide a Writer with the appropriate encoding yourself.

我的问题是我不知道如何提供作家......

// get the model from the map passed created by the controller
Object model = map.get("model");

Object viewData = transformViewData(model);

//TEST
Writer w = new OutputStreamWriter(viewData, "UTF-8");
//FINTEST

// if the model is null, we have an exception
String xml = null;
if (viewData != null){
    xml = xstream.toXML(viewData, w);  //Err:Cannot find symbol...
}else{
    // so render entire map
    xml = xstream.toXML(map, w); //Err:Cannot find symbol...
}

response.getOutputStream().write(xml.getBytes());

3 个答案:

答案 0 :(得分:1)

这是right there in the javadoc

Writer w = new OutputStreamWriter(new FileOutputStream("test.xml"), "UTF-8");
XStream.toXML(object, w);

答案 1 :(得分:1)

最后,它正在工作!!!

我修复了在xml.getByte()中添加“UTF-8”:

response.getOutputStream().write(xml.getBytes("UTF-8"));

答案 2 :(得分:0)

实际上,我在这里感到有些困惑。

Xstream做得很好,让我解释一下原因。

在文本编辑器中打开xml时,“特殊字符”被弄乱了;事实是,您不应该首先在文本编辑器中打开xml!

请记住,Xml和Html是孪生的languanges(第一个用于携带数据,第二个用于显示数据),就像html文件一样, xml文件也应该由网络浏览器打开。

因此Xstream替换了字符串中的“特殊字符”,以便您可以在Web浏览器中正确读取它。