XSLT if - 属性等于字符串 [英] XSLT if - attribute equals string
问题描述
我正在使用 xsl:if
在较大的 xsl:template
块中执行一个小条件,我想测试一个属性的相等性当前 xsl:template
匹配的节点.
I'm using a xsl:if
to perform a small condition in a larger xsl:template
block, and I'd like to test equality of an attribute of the current xsl:template
matched node.
以下不起作用:
<xsl:template match="sometag[@type='sometype']">
==Sometag==
<xsl:if test="@something!='hidden'">something</xsl:if>
<!--a lot of other stuff that I don't want to duplicate by multiplying the xsl:templates-->
<xsl:template>
这个测试似乎总是评估为假,也许我没有好的语法?
This test seems to be always evaluating to false, maybe I don't have the good syntax?
这个 XML:
<sometag type="sometype" something="visible"/>
<sometag type="sometype" something="hidden"/>
<sometag type="sometype"/>
应该给
==Sometag==
something...
==Sometag==
==Sometag==
something...
推荐答案
第二个标签不应打印某物"部分.
the 2nd tag should not get the "something" part printed.
我不完全确定您要实现的目标,但我会尝试一下.
I am not entirely sure what you are trying to achieve, but I'll give it a try.
您的一个 sometag
元素根本没有 something
属性.没有这个属性与 @something!='hidden'
完全不同.因此,如果 something
属性不存在,则不会输出字符串something".
One of your sometag
elements does not have a something
attribute at all. Not having this attribute is entirely different from @something!='hidden'
. So, the string "something" is not output if the something
attribute is not present.
因此,您需要在评估 xsl:if
条件之前测试是否存在 something
属性.
Because of this you need to test whether there is a something
attribute before your xsl:if
condition is evaluated.
输入
<?xml version="1.0" encoding="utf-8"?>
<root>
<sometag type="sometype" something="visible"/>
<sometag type="sometype" something="hidden"/>
<sometag type="sometype"/>
</root>
样式表
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/root">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="sometag[@type='sometype']">
<xsl:text>==Sometag==</xsl:text>
<xsl:choose>
<xsl:when test="@something">
<xsl:if test="@something!='hidden'">
<xsl:text>something</xsl:text>
</xsl:if>
</xsl:when>
<xsl:otherwise>
<xsl:text>something</xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
编辑 @Tim C 建议了一个更短的版本:
EDIT @Tim C has suggested an even shorter version:
<xsl:template match="sometag[@type='sometype']">
<xsl:text>==Sometag==</xsl:text>
<xsl:if test="@something!='hidden' or not(@something)">
<xsl:text>something</xsl:text>
</xsl:if>
</xsl:template>
输出
==Sometag==something==Sometag====Sometag==something
这篇关于XSLT if - 属性等于字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!