我正在研究应该使用某些样式表转换输出的过滤器。代码的重要部分如下所示:
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());
问题是国家字符被编码为 html 实体,而不是使用 UTF。有没有办法强制转换器使用 UTF-8 而不是实体?
最佳答案
您需要将输出方法设置为 text
而不是(默认)xml
。
transformer.setOutputProperty(OutputKeys.METHOD, "text");
但是,您还应该预先设置响应编码:
response.setCharacterEncoding("UTF-8");
并指示网络浏览器使用相同的编码:
response.setContentType("text/html;charset=UTF-8");
关于java - 如何强制 javax xslt 转换器使用 utf-8 而不是 html 实体对国家字符进行编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3029400/