2009-01-15 72 views
5

我将一串键值对作为参数传递给XSL(日期 - >“1月20日”,作者 - >“Dominic Rodger”,...)。XSLT中的动态变量

这些在一些XML我解析引用 - 在XML看起来是这样的:

<element datasource="date" /> 

目前,我无法工作,如何1月20日摆脱这些除了与一个可怕的<xsl:choose>声明:

<xsl:template match="element"> 
    <xsl:choose> 
    <xsl:when test="@datasource = 'author'"> 
     <xsl:value-of select="$author" /> 
    </xsl:when> 
    <xsl:when test="@datasource = 'date'"> 
     <xsl:value-of select="$date" /> 
    </xsl:when> 
    ... 
    </xsl:choose> 
</xsl:template> 

我想使用类似:

<xsl:template match="element"> 
    <xsl:value-of select="${@datasource}" /> 
</xsl:template> 

但我怀疑这是不可能的。我打算使用外部函数调用,但希望避免在我的XSL中枚举所有可能的映射键。有任何想法吗?

感谢,

大教堂

+0

请别注意,从提出的三个答案,两者是不正确的 - 没有一个“+”操作符在XPath的字符串,而且,AVT不能为“选择”指定属性在XSLT中。我的解决方案已经过测试和工作 – 2009-01-30 00:05:19

回答

2

这里是一个可能的解决方案,不过我建议你把所有的参数在一个单独的XML文件,并与document()功能访问它们:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:ext="http://exslt.org/common" 
exclude-result-prefixes="ext" 
> 
<xsl:output method="text"/> 

<xsl:param name="date" select="'01-15-2009'"/> 
<xsl:param name="author" select="'Dominic Rodger'"/> 
<xsl:param name="place" select="'Hawaii'"/> 
<xsl:param name="time" select="'midnight'"/> 

<xsl:variable name="vrtfParams"> 
    <date><xsl:value-of select="$date"/></date> 
    <author><xsl:value-of select="$author"/></author> 
    <place><xsl:value-of select="$place"/></place> 
    <time><xsl:value-of select="$time"/></time> 
</xsl:variable> 

<xsl:variable name="vParams" select="ext:node-set($vrtfParams)"/> 

    <xsl:template match="element"> 
     <xsl:value-of select= 
     "concat('&#xA;', @datasource, ' = ', 
       $vParams/*[name() = current()/@datasource] 
       )" 
     /> 
    </xsl:template> 
</xsl:stylesheet> 

当下面的XML应用这种转变文档

<data> 
    <element datasource="date" /> 
    <element datasource="place" /> 
</data> 

正确的结果产生

日期= 2009年1月15日

地方=夏威夷

待办事项使用xxx:node-set()功能(the EXSLT one这里使用)至RTF(Result Tree Fragment)转换为常规XML文档(临时树)。

-2

如何

<xsl:template match="date-element"> 
    <xsl:text>${date}</xsl:text> 
</xsl:template> 

即而不是使用不同的元素名称使用属性,匹配。

如果您无法更改源XML,请通过将属性转换为正确元素名称的小型XSLT来运行它。

另一种解决方案是将xsl:param元素放入不同的XML文档(或尝试使XSLT模板再次自我阅读)。然后你可以使用xsl:key和key()来引用它们。

[编辑]用xsl:text取代xsl:value-of。我没有XSLT util,所以我无法测试它。如果这不起作用,请发表评论。

+0

对不起,但“select”属性是唯一不能指定AVT(Attribute-value-templates)的属性。 – 2009-01-30 00:02:39

0

如果您的@datasource始终与参数名称匹配,则可以尝试“评估”功能。注意:此代码未经测试。

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:exslt-dynamic="http://exslt.org/dynamic" 
> 

<xsl:param name="date"/> 

<xsl:template match="element"> 
    <xsl:value-of select="exslt-dynamic:evaluate('$' + @datasource)"/> 
</xsl:template> 

</xsl:stylesheet> 
+1

确实没有经过测试。在XPath中,不能求和('+')字符串 - 这将永远不会编译。 – 2009-01-30 00:00:12