如何使用contains()函数检查字符串是否存在预定义的子串和count()匹配的字符串?

时间:2015-12-26 06:47:51

标签: xml count xslt-1.0 contains

我试图检查字符串是否存在预定义的子串,然后想要计算()匹配这些格式的元素或字符串。我的例子现在跟着......

<!-- xslt code snippet | this is what i did, but i don,t know how to count() them, i,m getting something like 111 as output :|-->
<xsl:for-each select="automobile">
    <xsl:if test="contains(name_and_class, 'J.TK') or
        contains(name_and_class, 'P.LO') or contains(name_and_class, 'M.GA')">
        <xsl:value-of select="name_and_class"/>
 <!-- please help me to count() them here-->

 <!-- xml code snippet -->
<automobile>
<name_and_class>Mercedes B.OO</name_and_class>
</automobile>
<automobile>
<name_and_class>Hummer P.LO</name_and_class>
</automobile>
<automobile>
<name_and_class>Audi J.TK</name_and_class>
</automobile>
<automobile>
<name_and_class>Ferrari M.GA</name_and_class>
</automobile>
<automobile>
<name_and_class>Mercedes F.BQ</name_and_class>
</automobile>

1 个答案:

答案 0 :(得分:0)

您可以使用谓词([]中的表达式)来过滤元素,例如假设我们将以下格式良好的XML作为输入:

<root>
    <automobile>
    <name_and_class>Mercedes B.OO</name_and_class>
    </automobile>
    <automobile>
    <name_and_class>Hummer P.LO</name_and_class>
    </automobile>
    <automobile>
    <name_and_class>Audi J.TK</name_and_class>
    </automobile>
    <automobile>
    <name_and_class>Ferrari M.GA</name_and_class>
    </automobile>
    <automobile>
    <name_and_class>Mercedes F.BQ</name_and_class>
    </automobile>
</root>

此模板将在不使用name_and_class的情况下输出符合条件的xsl:for-each个元素的数量:

<xsl:template match="/root">
    <xsl:value-of select="count(automobile[
        contains(name_and_class, 'J.TK') or
        contains(name_and_class, 'P.LO') or 
        contains(name_and_class, 'M.GA')
        ])"/>
</xsl:template>

<强> xsltransform demo

输出:

3