[英]XSLT 2.0 generate ouput filename from xml
我有一點問題。 我必須使用XSLT從XML文件中生成HTML文件。 但是HTML文件名是由XML內容生成的。 就我而言,我解決了以下問題:
public File GenerateHTML(File fileIn) {
File xsltFile = new File(xsltfileString);
File htmlFile = new File(System.getProperty("user.home") + File.separator + "result.html");
File htmlFileFinal = null;
Source xmlSource = new StreamSource(fileIn);
Source xsltSource = new StreamSource(xsltFile);
Result htmlResult = new StreamResult(htmlFile);
TransformerFactory transFact = TransformerFactory.newInstance();
Transformer trans;
try {
trans = transFact.newTransformer(xsltSource);
trans.setParameter("filter_xml", filterXML);
trans.setParameter("FileName", fileIn.getName());
trans.transform(xmlSource, htmlResult);
String outputFileName = (String)trans.getParameter("OutputFilename");
htmlFileFinal = new File(System.getProperty("user.home") + File.separator + outputFileName + ".html");
htmlFile.renameTo(htmlFileFinal);
} catch (TransformerConfigurationException ex) {
LOGGER.log(Level.FATAL, ex.getMessage(), ex);
} catch (TransformerException ex) {
LOGGER.log(Level.FATAL, ex.getMessage(), ex);
}
return htmlFileFinal;
}
在我的XSLT中,我這樣做:
<!-- general settings -->
<xsl:output method="html" omit-xml-declaration="yes" indent="yes" encoding="UTF-8" />
<xsl:variable name="filter" select="document($filter_xml)/Filtre/Bloc5" />
<!-- transformation body -->
<xsl:template match="*">
<xsl:param name="OutputFilename" select="concat(cac:ContractDocumentReference/cbc:ID, '_', cbc:ID, '_', translate(cbc:IssueDate, '-', ''))" />
[...]
此解決方案有效,但我問自己是否經過優化或XSLT中是否有技巧來生成動態輸出文件名?
借助XSLT 2.0,您當然可以基於XML輸入值創建名稱分別為URL的結果文檔,例如
<xsl:template match="/">
<xsl:result-document href="{root/foo/bar}.xml">
<xsl:apply-templates/>
</xsl:result-document>
</xsl:template>
您也可以從命名模板開始,例如
<xsl:template name="main">
<xsl:variable name="doc1" select="doc('input.xml')"/>
<xsl:result-document href="{$doc1/root/foo/bar}.xml">
<xsl:apply-templates select="$doc1/node()"/>
</xsl:result-document>
</xsl:template>
盡管我不確定您所使用的JAXP轉換API是否適合它。
您也可以完全避免使用for-each。 ...從有效的xslt中獲取。
<xsl:template match="EXTRACT-DATASETS/SUBSET">
...
...
<xsl:result-document href="{$filename-stub}.ctl">
...
...
</xsl:result-document>
</xsl:template>
這將為找到的每個匹配項生成一個文件。 變量filename-stub在主模板中計算。 不需要每個...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.