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

How to use contains() function to check in strings the presence of predefined substrings and count() the strings that match?

我正在尝试检查字符串中是否存在预定义的子字符串,然后想要计算 () 与这些格式匹配的元素。

我的例子如下:

<!-- 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