[英]How can I get XSLT to return UTF-8 in Java
我正在尝试让XSL脚本与UTF-8编码一起使用。 åäö和希腊字母等字符就像垃圾一样出现。 使其正常工作的唯一方法是将结果写入文件。 如果我将其写入输出流,它只会返回垃圾(System.out可以正常工作,但这可能是因为它的蜂鸣重定向到了文件)。
需要从servlet返回结果,请注意,它不是servlet配置问题。 我可以从servlet返回带有希腊字符的硬编码字符串,并且它可以正常工作,因此这是转换的问题。
这是我当前的(简体)代码。
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException,
IOException {
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
final TransformerFactory factory = this.getFactory();
final File inFile = new File("infile.xml");
final File xslFile = new File("template.xsl");
final File outFile = new File("outfile.html");
final Templates templates = factory.newTemplates(new StreamSource(xslFile));
final Transformer transformer = templates.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
final InputStream in = new FileInputStream(inFile);
final StreamSource source = new StreamSource(in);
final StreamResult result1 = new StreamResult(outFile);
final StreamResult result2 = new StreamResult(System.out);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final StreamResult result3 = new StreamResult(out);
//transformer.transform(source, result1);
//transformer.transform(source, result2);
transformer.transform(source, result3);
final Writer writer = response.getWriter();
writer.write(new String(out.toByteArray()));
writer.close();
in.close();
} catch (final TransformerConfigurationException e) {
e.printStackTrace();
} catch (final TransformerException e) {
e.printStackTrace();
}
}
另外,我的XSL脚本包含以下内容
<xsl:output method="html" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
使它正常工作的正确方法是什么? 我正在使用Saxon进行转换,如果有帮助的话。
这几乎可以肯定是问题所在:
writer.write(new String(out.toByteArray()));
您已经将文本仔细编码为UTF-8,然后使用平台默认编码转换为字符串。 您几乎应该永远不要使用使用平台默认编码的String
构造函数和方法。 即使您想使用该编码,也要明确使用。
如果仍然要写入Writer
,为什么要开始写入ByteArrayOutputStream
? 为什么不直接找Writer
?
但是,最好直接写入响应的输出流( response.getOutputStream()
),并设置响应的内容类型以表明它是UTF-8,这样会更好。
请注意,如果您确实想预先获得作为String
的结果,请使用StringWriter
。 写入ByteArrayOutputStream
然后转换为字符串没有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.