Xslt XSL根据条件添加属性
xslt中是否有一行if条件,比如假设我只想基于某个条件添加属性 e、 gXslt XSL根据条件添加属性,xslt,Xslt,xslt中是否有一行if条件,比如假设我只想基于某个条件添加属性 e、 g 只是为了避免 <xsl:if test="true"> <name defineAttribute/> </xsl:if> 您可以使用创建输出元素,并为其属性创建。然后添加条件属性很简单: <xsl:element name="name"> <xsl:if test="condition"> <xsl:attribute nam
只是为了避免
<xsl:if test="true">
<name defineAttribute/>
</xsl:if>
您可以使用
创建输出元素,并为其属性创建
。然后添加条件属性很简单:
<xsl:element name="name">
<xsl:if test="condition">
<xsl:attribute name="myattribute">somevalue</xsl:attribute>
</xsl:if>
</xsl:element>
一些价值
以下是一个示例,说明如何完全避免指定
:
让我们来看看这个XML文档:
<a x="2">
<b/>
</a>
<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>
<a x="2">
<b parentEven="true"/>
</a>
将此转换应用于上述XML文档时,将生成所需的正确结果:
<a x="2">
<b/>
</a>
<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>
<a x="2">
<b parentEven="true"/>
</a>
注意事项:
<a x="2">
<b/>
</a>
<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>
<a x="2">
<b parentEven="true"/>
</a>
使用模板和模式匹配可以完全消除指定显式条件指令的需要。XSLT代码中出现显式条件指令应被视为“代码气味”,应尽可能避免。我想说的是,您必须在打开元素后立即执行此操作。你不能先做其他事情。