我想知道XSLT中是否有一种方法可以修改/添加属性值。
现在我只是简单地替换属性值:
<a class="project" href="#">
<xsl:if test="new = 'Yes'">
<xsl:attribute name="class">project new</xsl:attribute>
</xsl:if>
</a>
但是我不喜欢第2行中重复的project
。是否有更好的方法来做到这一点,例如,简单地在属性的末尾添加 new
?
谢谢你的帮助!
您可以将if
放在attribute
中,而不是相反:
<a href="#">
<xsl:attribute name="class">
<xsl:text>project</xsl:text>
<xsl:if test="new = 'Yes'">
<xsl:text> new</xsl:text>
</xsl:if>
</xsl:attribute>
</a>
<xsl:attribute>
可以包含任何有效的XSLT模板(包括for-each
循环、应用其他模板等),唯一的限制是实例化该模板必须只生成文本节点,而不能生成元素、属性等。属性值将是所有这些文本节点的连接。
在XSLT 1.0中可以使用以下一行代码:
<a class="project{substring(' new', 5 - 4*(new = 'Yes'))}"/>
这是一个完整的转换:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/*">
<a class="project{substring(' new', 5 - 4*(new = 'Yes'))}"/>
</xsl:template>
</xsl:stylesheet>
当此转换应用于以下XML文档时:
<t>
<new>Yes</new>
</t>
生成所需的正确结果:
<a class="project new"/>
:
AVT(属性值模板)的使用
要根据条件选择字符串,在XPath 1.0中可以使用子字符串函数并指定一个表达式作为起始索引参数,当条件为
true()
时,该表达式求值为1,否则求值为大于字符串长度的某个数字。我们使用这样一个事实:在XPath 1.0中,
*
(乘法)运算符的任何参数都被转换为数字,并且number(true()) = 1
和number(false()) = 0
二世。XSLT 2.0解决方案:
使用下面的一行代码:
<a class="project{(' new', '')[current()/new = 'Yes']}"/>
这是一个完整的转换:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/*">
<a class="project{(' new', '')[current()/new = 'Yes']}"/>
</xsl:template>
</xsl:stylesheet>
当应用于相同的XML文档(如上)时,同样想要的,产生正确的结果:
<a class="project new"/>
:
正确使用AVT。
正确使用序列。
正确使用XSLT
current()
函数