How can you pass in a parameter to an xslt that ca

2019-02-28 13:33发布

This XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:param name="paramvalue" />
  <xsl:key name="test" match="$paramvalue" use="generate-id()" />

  <!-- template rules -->
</xsl:stylesheet>

Fails because you can't seem to have a parameter value in the match attribute of an xsl:key. Is there any way to do this other than modifying the xslt on the fly?

标签: xslt
2条回答
ゆ 、 Hurt°
2楼-- · 2019-02-28 13:35

First, it's a strange requeriment because mostly every time one wants to know wich nodes a key is matching. But besides that, and @Dimitre's excellent answer (use XSLT 2.0), you can use and external input source as parameter with document() function.

This stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:key name="Key"
             match="*[name() = document('param.xml')/*/param]"
             use="generate-id()"/>
    <xsl:template match="text()"/>
    <xsl:template match="*[key('Key',generate-id())]">
        <xsl:copy-of select="."/>
    </xsl:template>
</xsl:stylesheet>

With this input (also known as 'param.xml'):

<root>
    <param>data</param>
    <data>something</data>
</root>

Output:

<data>something</data>
查看更多
别忘想泡老子
3楼-- · 2019-02-28 13:42

How can you pass in a parameter to an xslt that can be used in a xsl:key?

Use XSLT 2.0 for this.

In XSLT 1.0 "It is an error for the value of either the use attribute or the match attribute to contain a VariableReference." as per spec

This limitation was put in the spec with the goal of preventing a chain of circular references.

Is there any way to do this other than modifying the xslt on the fly?

Yes, your XSLT code may generate a new xslt stylesheet that uses the specific value of the parameter in the definition of the key.

Or, in case the values of the parameter are from a finite set, you may have keys defined for every possible value -- and the parameter itself will contain the name of the key to use -- do note that the key-name argument of the key() function can be any expression, including variable references.

查看更多
登录 后发表回答