如何为XSL生成的表格行正确设置带前缀的递增ID?
解决XSLT中动态设置元素ID的问题
你当前的写法错误在于直接在HTML属性中嵌套<xsl:value-of>,这不符合XSLT的语法规范,Firefox提示格式不正确正是因为这个原因。下面提供两种正确的实现方式:
方法1:使用属性值模板(推荐)
属性值模板是XSLT中简化动态属性生成的语法,用大括号{}包裹XPath表达式即可:
<xsl:template match="item"> <xsl:variable name="item.count" select="count(preceding::item)" /> <tr id="item-{$item.count}"> <xsl:comment><xsl:value-of select="$item.count" />: <xsl:value-of select="." /></xsl:comment> <xsl:apply-templates select="./*"/> <!-- ... --> <td>(output)</td> </tr> </xsl:template>
方法2:使用<xsl:attribute>元素
如果需要更复杂的属性生成逻辑,可以显式使用<xsl:attribute>来创建ID属性:
<xsl:template match="item"> <xsl:variable name="item.count" select="count(preceding::item)" /> <tr> <xsl:attribute name="id">item-<xsl:value-of select="$item.count" /></xsl:attribute> <xsl:comment><xsl:value-of select="$item.count" />: <xsl:value-of select="." /></xsl:comment> <xsl:apply-templates select="./*"/> <!-- ... --> <td>(output)</td> </tr> </xsl:template>
额外补充:count(preceding::item)会统计当前节点之前所有的item节点,计数从0开始。如果需要从1开始递增,可以改成count(preceding::item) + 1。
内容的提问来源于stack exchange,提问作者U. Windl
相关产品推荐
相关产品推荐

