我需要一种干预写入 xsl 结果文档的方法,以避免将它们写入文件系统。现在我的模板正在写入一个临时目录,然后我压缩该目录。我想写到文件系统。我正在使用撒克逊处理器。最好使用仅使用标准 java 库的解决方案。任何建议表示赞赏。
编辑:我为 .net saxon api http://www.saxonica.com/documentation/dotnetdoc/Saxon/Api/IResultDocumentHandler.html找到了这个类 我需要与 java 等效的东西。
我需要一种干预写入 xsl 结果文档的方法,以避免将它们写入文件系统。现在我的模板正在写入一个临时目录,然后我压缩该目录。我想写到文件系统。我正在使用撒克逊处理器。最好使用仅使用标准 java 库的解决方案。任何建议表示赞赏。
编辑:我为 .net saxon api http://www.saxonica.com/documentation/dotnetdoc/Saxon/Api/IResultDocumentHandler.html找到了这个类 我需要与 java 等效的东西。
您需要实现接口net.sf.saxon.OutputURIResolver
http://www.saxonica.com/documentation/javadoc/net/sf/saxon/lib/OutputURIResolver.html
您可以根据需要在解析方法中重定向输出。就我而言,这就是实现类的样子。
public class ZipOutputURIReslover implements OutputURIResolver{
private ZipOutputStream zipOut;
public ZipOutputURIReslover(ZipOutputStream zipOut) {
super();
this.zipOut = zipOut;
}
public void close(Result arg0) throws TransformerException {
try {
zipOut.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
}
public Result resolve(String href, String base) throws TransformerException {
try {
zipOut.putNextEntry(new ZipEntry(href));
} catch (IOException e) {
e.printStackTrace();
}
return new StreamResult(zipOut);
}
}
在此之后,您需要注册net.sf.saxon.OutputURIResolver
到变压器工厂。
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream("file.zip"));
factory.setAttribute("http://saxon.sf.net/feature/outputURIResolver", new ZipOutputURIReslover(zipOut));
当您加载模板并运行转换时,所有 xsl:result-documents 将直接写入 zipOutputStream。
在这里找到了答案http://sourceforge.net/p/saxon/discussion/94027/thread/9ee79dea/#70a9/6fef
new StreamResult(ByteArrayOutputStream())
如果您不想写入文件,您可以使用捕获 xslt 输出,然后您可以使用这种方法将内存数据从字节数组保存到 zip 文件在 Java 中:如何从字节 [] 数组压缩文件?
请注意,最新版本的 Saxon 要求 href (URI) 是唯一的。因此,输出解析器中流的系统 ID 也必须是唯一的。
例如:
在样式表中指定结果文档的 href 值
<xsl:result-document href="{$filename}" method="text">
创建输出解析器
public class ZipOutputURIReslover implements OutputURIResolver{
private ZipOutputStream zipOut;
public ZipOutputURIReslover(ZipOutputStream zipOut) {
super();
this.zipOut = zipOut;
}
public void close(Result arg0) throws TransformerException {
try {
zipOut.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
}
public Result resolve(String href, String base) throws TransformerException {
try {
zipOut.putNextEntry(new ZipEntry(href));
} catch (IOException e) {
e.printStackTrace();
}
Result result = new StreamResult(zipOut);
// Must ensure the stream is given a unique ID
result.setSystemId(UUID.randomUUID().toString());
return result;
}
}
将输出旋转变压器连接到变压器
ZipOutputURIResolver outputResolver = new ZipOutputURIResolver(outputStream);
// Controller is the Saxon implementation of the JAXP Transformer
((Controller) transformer).setOutputURIResolver(outputResolver);