[英]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.