2012-09-26 43 views
0

我有一点问题。我必须使用XSLT从XML文件生成HTML文件。但是HTML文件名是由XML内容生成的。 在我来说,我解决我的问题如下:XSLT 2.0从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中生成一个动态输出文件名是一个窍门吗?

回答

3

对于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。

+0

我问myslef是否有一个技巧,可以轻松地将XML文档转换为HTML文档,其中XML文件名已从XML内容生成。 –

+0

这不是一招:马丁向你展示了如何去做。你的代码在做什么我无法开始理解。 trans.getParameter()不应该以你使用它的方式返回任何东西。 –

+0

@ginogure,我的代码示例创建了一个结果文档,其中名称是根据对XPath表达式“root/foo/bar”的计算结果构建为带有这些元素和字符串“.xml”的虚构输入文档的结果文档。因此,修改该路径表达式以适合您的输入文档,并且您有正确的方法。或者发布你的输入样本,并告诉我们它应该定义文件名的哪一部分。 –

0

你也可以完全避免for-each。 ...从工作xslt。

<xsl:template match="EXTRACT-DATASETS/SUBSET"> 
... 
... 
<xsl:result-document href="{$filename-stub}.ctl"> 
... 
... 
</xsl:result-document> 
</xsl:template> 

这将为它找到的每个匹配项生成一个文件。变量文件名存根在主模板内计算。没有为每个需要....