在xslt中将属性作为参数传递给现有元素



我正在使用XSLT向现有xml添加一个属性。我可以用固定的值来实现。但是想要传递所需的数据作为参数,而不是硬编码它。到目前为止我所做的如下:

输入XML:

<Student id='5' name="John" />

我的XSLT代码如下所示:

<xsl:template match="/">
<xml>           
<xsl:call-template name="Copy" >                                    
</xsl:call-template>
</xml>
</xsl:template>
<xsl:template match="Student/@age">
<xsl:attribute name="age">
<xsl:value-of select="'98'"/>
</xsl:attribute>
</xsl:template>

<xsl:template match="Student">
<xsl:copy>
<xsl:attribute name="age">
<xsl:value-of select="'45'"/>
</xsl:attribute>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template name="Copy" match="node()|@*">    
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>

输出为:

<xml><Student age="45" id="5" name="John"/></xml>

现在我的问题是,而不是硬编码的值,我需要传递它作为一个参数使用<xsl:with-param />,但我没有得到预期的输出。谁能帮我一下?

更新:我将从我将要读取的其他xml中获取参数,现在我添加了一个变量,如下所示:

<xsl:variable name="attributeValue" >
<xsl:value-of select="'NewData'"/>
</xsl:variable>
<xsl:call-template name="Copy" >
<xsl:with-param name="AttributeValue">
<xsl:value-of select="$attributeValue"/>
</xsl:with-param>
</xsl:call-template>

如果您知道在哪里查找"其他xml"中的值,则可以使用全局变量而不是参数,并避免使用所有<xsl:with-param>元素。例如,如果另一个XML看起来像

<OtherData>
<Age>45</Age>
...
</OtherData>

你可以写

<xsl:variable name="attributeValue" select="document('http://path/to/other/xml')//Age"/>

在您的转换的顶层。然后它将作为$attributeValue在所有模板中可用。

相关内容