java - 带有特殊字符的 Xstream

标签 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.

我的问题是我不知道如何提供 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());

最佳答案

这是 right there in the javadoc .

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

关于java - 带有特殊字符的 Xstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5250312/

相关文章:

asp.net - 如何使用 ASP.NET 注入(inject)包含 & 符号的脚本 URL?

python获取unicode字符串大小

php - 更改 MySQL、PHP 脚本、HTML 中的字符编码

java - resque :failed and resque:stat:failed keys?有什么区别

java - 有没有一种方法可以编写与原始数组类型一起使用的通用 Java 方法?

java - 如何编写需要密码才能满足某些要求的单一方法?

消费者接口(interface)中的 Java 泛型类型参数

python - python/nautilus 脚本组合的奇怪字符编码问题

c# - 尽管原始类型如何,我如何强制将每个字符串编码为 UTF8?

.net - 用于学习不同类型的字符编码以及它们之间转换的良好资源