JMira
JMira

Reputation: 888

Xstream with special characters

I'm working with XStream but I have a problem with the special characters á,é,í,ó,ú and ñ.

I tried this:

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

(don't work)

I found that 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.

My problem is that I don't know how to provide a Writer...

// 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());

Upvotes: 0

Views: 6653

Answers (3)

BabaNew
BabaNew

Reputation: 986

Actually, i sense a little bit of confusion here.

Xstream is doing the job just fine, let me explain why.

"Special characters" are messed up when you open the xml in a text editor; the fact is that you shouldn't open the xml in a text editor in the first place!

Keep in mind that Xml and Html are twinned languanges(the first intended to carry data, the latter intended to display data), and just like html files also xml files are supposed to be opened by a web browser.

So Xstream replaces the "special characters" in the string so that you can correctly read it in a web browser.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692231

It's right there in the javadoc.

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

Upvotes: 2

JMira
JMira

Reputation: 888

Finally, it's working !!!

I fix it adding "UTF-8" in xml.getByte():

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

Upvotes: 1

Related Questions