如何将 xslt 模板应用于字符串? [英] How can I apply an xslt template to a string?
问题描述
给定一个用于围绕一个值构建一些 html 的模板,我想传入一个字符串,而不是一个节点集.例如,我想连接一些值并将其传递给模板.我怎样才能实现那种事情?
Given a template used for building some html around a value, I want to pass in a string, rather than a node set. As an example I want to concat some values and pass that to the template. How can I achieve that sort of thing?
<xsl:template match="text()" mode="kvp-print-single">
<tr>
<td colspan="3"><xsl:value-of select="."/></td>
</tr>
</xsl:template>
...
<xsl:apply-templates select="concat=(haba/hiba:text(), ' - ', huba/baba:text())" mode="kvp-print-single"/>
ErrorMsg: xml 或样式表文件无效!
ErrorMsg: xml or stylesheet file is invalid!
异常:System.Xml.Xsl.XsltException:表达式必须计算为节点集.
Exception: System.Xml.Xsl.XsltException: Expression must evaluate to a node-set.
推荐答案
如果目的是代码重用,要在多个地方使用模板,那么你可以做的就是给你的模板一个名字(除了模板匹配),并给它一个默认参数
If the aim is code re-use, to use the template in multiple places, then what you could do is give your template a name (in addition to the template match), and give it a default parameter
<xsl:template match="text()" name="kvp-print-single" mode="kvp-print-single">
<xsl:param name="text" select="." />
<tr>
<td colspan="3"><xsl:value-of select="$text"/></td>
</tr>
</xsl:template>
然后只需使用 xsl:call-template 将连接的字符串作为参数调用它
Then just use xsl:call-template to call it with you concatenated string as a parameter
<xsl:call-template name="kvp-print-single">
<xsl:with-param name="text" select="concat(haba/hiba:text(), ' - ', huba/baba:text())" />
</xsl:call-template>
注意,当使用xsl:apply-templates进行匹配时,模板仍然会以正常方式匹配text()"节点.
Note, the template will still match "text()" nodes in the normal way when matched using xsl:apply-templates.
这篇关于如何将 xslt 模板应用于字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!