如果xslt中的条件有任何一行,例如假设我只想根据某些条件添加属性
例如
<name (conditionTrue then defineAttribute)/>
Run Code Online (Sandbox Code Playgroud)
只是为了避免
<xsl:if test="true">
<name defineAttribute/>
</xsl:if>
Run Code Online (Sandbox Code Playgroud)
您可以使用它<xsl:element>来创建输出元素<xsl:attribute>及其属性.然后添加条件属性很简单:
<xsl:element name="name">
<xsl:if test="condition">
<xsl:attribute name="myattribute">somevalue</xsl:attribute>
</xsl:if>
</xsl:element>
Run Code Online (Sandbox Code Playgroud)
以下是如何完全避免指定的一个示例<xsl:if>:
我们有这个XML文档:
<a x="2">
<b/>
</a>
Run Code Online (Sandbox Code Playgroud)
并且我们只想在's parent 的属性值是偶数时才添加b属性.parentEven="true"xb
以下是没有任何明确条件指令的方法:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="a[@x mod 2 = 0]/b">
<b parentEven="true">
<xsl:apply-templates select="node()|@*"/>
</b>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
在上面的XML文档中应用此转换时,会生成所需的正确结果:
<a x="2">
<b parentEven="true"/>
</a>
Run Code Online (Sandbox Code Playgroud)
请注意:
使用模板和模式匹配可以完全消除指定显式条件指令的需要.XSLT代码中存在显式条件指令应被视为"代码气味",应尽可能避免.
| 归档时间: |
|
| 查看次数: |
9965 次 |
| 最近记录: |