How to force javax xslt transformer to encode national characters using utf-8 and not html entities?

為{幸葍}努か 提交于 2019-12-08 09:17:59

问题


I'm working on filter that should transform an output with some stylesheet. Important sections of code looks like this:

PrintWriter out = response.getWriter();
...
StringReader sr = new StringReader(content);
Source xmlSource = new StreamSource(sr, requestSystemId);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setParameter("encoding", "UTF-8");
//same result when using ByteArrayOutputStream xo = new java.io.ByteArrayOutputStream();
StringWriter xo = new StringWriter();
StreamResult result = new StreamResult(xo);
transformer.transform(xmlSource, result);
out.write(xo.toString());

The problem is that national characters are encoded as html entities and not by using UTF. Is there any way to force transformer to use UTF-8 instead of entities?


回答1:


You need to set the output method to text instead of (default) xml.

transformer.setOutputProperty(OutputKeys.METHOD, "text");

You should however also set the response encoding beforehand:

response.setCharacterEncoding("UTF-8");

And instruct the webbrowser to use the same encoding:

response.setContentType("text/html;charset=UTF-8");


来源:https://stackoverflow.com/questions/3029400/how-to-force-javax-xslt-transformer-to-encode-national-characters-using-utf-8-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!