Saxon XSLT 转换为字符串而不是文件

Fuz*_*sis 2 java xslt saxon

在下面的 Java 代码中,我通过转换存储在字符串中的生成的 xml 数据来创建 *.html 报告,

combinedDDIString

...针对 XSLT 文件,

reportXSLT
Run Code Online (Sandbox Code Playgroud)

...并将结果写入物理文件,

tmpReportHTML

然后,代码将文件读回到字符串中,以便在其他方法中使用。我想避免将结果写入文件,只需将结果直接转换为字符串即可。

有什么方法可以将转换结果直接写入字符串,并避免将结果写入物理文件?

    String reportString = null;
    FileInputStream stream = null;
    ByteArrayOutputStream reportBAOS = new ByteArrayOutputStream(); 

try {

    System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
    transformerFactory = TransformerFactory.newInstance();
    transformer = transformerFactory.newTransformer(new StreamSource(reportXSLT));
    transformer.setOutputProperty(OutputKeys.ENCODING, "US-ASCII");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    /*
     * Create a new report file time-stamped for uniqueness, to avoid concurrency issues
     */
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    Date date = new Date();
    File tmpReportHTML = new File(reportHTML + dateFormat.format(date) + ".html");

    /*
     * Perform the transform to get the report
     */
    FileOutputStream reportFOS = new FileOutputStream(tmpReportHTML);
    OutputStreamWriter osw = new OutputStreamWriter(reportFOS, "US-ASCII");//(reportBAOS), "US-ASCII");
    transformer.transform(new StreamSource(new StringReader(combinedDDIString)), new StreamResult(osw));
    osw.close();

    /*
     * Get the report as a string from the temp report file
     */
    //FileInputStream stream = new FileInputStream(new File(REPORT_OUTPUT)); 
    stream = new FileInputStream(tmpReportHTML); //(new File(reportXML));           
    FileChannel fc = stream.getChannel(); 
    MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); 
    reportString = Charset.defaultCharset().decode(bb).toString(); 

    /*
     * Delete the temp report file
     */
    tmpReportHTML.delete();


} catch (TransformerConfigurationException e) {
    e.printStackTrace();
} catch (Exception ex) {
    ex.printStackTrace();
}
finally { 
    stream.close(); 
Run Code Online (Sandbox Code Playgroud)

先谢谢您的帮助。

rcg*_*ves 5

尝试使用 aStringWriter创建StreamResult. (您应该能够String通过StringWriter简单地使用该toString方法获得一个。)