2012-11-20 38 views
2

我想让我的XSL脚本能够使用UTF-8编码。像åäö和希腊字符等字符就像垃圾一样起来。让它起作用的唯一方法是将结果写入文件。如果我将它写入输出流,它只会返回垃圾(System.out可以工作,但这可能是因为它的beeing被重定向到一个文件)。我怎样才能让XSLT在Java中返回UTF-8

结果需要从一个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" /> 

什么是得到这个工作的正确方法是什么?如果可能有任何帮助,我正在使用撒克逊进行转型。

回答

5

这是几乎可以肯定的问题:

writer.write(new String(out.toByteArray())); 

你已经仔细编码的文本为UTF-8,然后你正在使用的平台默认的编码转换成字符串。你应该差不多从来没有使用String构造函数和使用平台默认编码的方法。即使你想要使用该编码,明确地这样做。

如果你打算写一个Writer无论如何,你为什么开始写信给ByteArrayOutputStream?为什么不直接去Writer

但是,直接写入响应的输出流(response.getOutputStream())并设置响应的内容类型以表明它是UTF-8会更好。

请注意,如果您确实想事先将结果作为String,请使用StringWriter。写入ByteArrayOutputStream然后转换为字符串没有意义。

+0

谢谢,您指出我正确的方向。我刚刚发现'ByteArrayOutputStream'有方法'out.toString(“UTF-8”)'所以它在那之后工作。我无法立即使用响应流,因为我还有其他一些东西来处理结果,但我认为我现在可以做到这一点。谢谢! – Johan

+0

我正要回答这个问题,然后我看到@jonSkeet 0_0 –

+0

如果您希望输出作为一串字符由Java应用程序处理,只需让变形器输出字符即可,方法是提供一个Writer。要求将字节写入byteOutputStream,然后将字节解码为字符,只会造成复杂性和潜在的错误。 –