l15*_*15a 5 java xml xslt unicode utf-8
我的 XSLT 转换已经成功了几个月,直到我遇到带有 Unicode 字符(很可能是表情符号)的 XML 文件。我需要保留 Unicode,但 XSLT 正在将其转换为 HTML 实体。我认为将编码设置为 UTF-8 可以解决我的问题,但我仍然遇到问题。
任何帮助表示赞赏。代码:
private byte[] transform(InputStream stream) throws Exception{
System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.processor.TransformerFactoryImpl");
Transformer xmlTransformer;
xmlTransformer = (TransformerImpl) TransformerFactory.newInstance().newTransformer(new StreamSource(createXsltStylesheet()));
xmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(stream,"UTF-8");
Source staxSource = new StAXSource(reader, true);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(outputStream, "UTF-8");
xmlTransformer.transform(staxSource, new StreamResult(writer));
return outputStream.toByteArray();
}
Run Code Online (Sandbox Code Playgroud)
如果我添加
xmlTransformer.setOutputProperty(OutputKeys.METHOD, "text");
Run Code Online (Sandbox Code Playgroud)
Unicode 被保留,但 XML 不被保留。
这行代码很可疑:
stream = IOUtils.toInputStream(outputStream.toString(),"UTF-8");
Run Code Online (Sandbox Code Playgroud)
您正在ByteArrayOutputStream使用平台的默认编码(可能不是 UTF-8)将 a 转换为字符串。将其更改为
stream = IOUtils.toInputStream(outputStream.toString("UTF-8"),"UTF-8");
Run Code Online (Sandbox Code Playgroud)
或者,为了获得更好的性能,只需将字节数组包装在ByteArrayInputStream:
return new ByteArrayInputStream(outputStream.toByteArray());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4134 次 |
| 最近记录: |