2011-03-09 172 views
0

我正在使用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()); 

回答

1

最后,它的工作!

我解决它在xml.getByte(加入 “UTF-8”):

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

这是right there in the javadoc

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

我没有一个XML文件,我从地图获取数据。 – JMira

+0

新的OutputStreamWriter行(viewData,“UTF-8”)无效。 OutputStreamWriter将一个OutputStream作为参数。你想在哪里发送你的XML? –

+0

对于Web浏览器,该部分工作正常,问题是特殊字符。 – JMira