2011-03-09 166 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