如何使用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"/>
 <!-- how can I 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>

您可以使用谓词([]中的表达式)来过滤元素,例如,假设我们有以下格式良好的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>

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

<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

相关内容

  • 没有找到相关文章

最新更新