You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用XSL 2.0/3.0处理时统计<p>元素中特定字符组合的次数

使用XSL 2.0/3.0统计XHTML中

元素内特定字符组合的出现次数

针对你需要统计

元素中&amp;和&quot;这两个实体引用出现次数的需求,分两种场景给出实现方案:

场景1:统计原XHTML标记中的实体引用字符串(如&amp;、&quot;)

适用于需要统计原始代码里的实体引用,而非解析后的字符。此方案依赖XSLT 3.0的serialize()函数:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all">

    <xsl:output method="text" encoding="UTF-8"/>

    <xsl:template match="/">
        <!-- 序列化所有<p>的子节点,还原原始标记中的实体引用 -->
        <xsl:variable name="p-markup" select="serialize(//p/node(), map{'method':'xml', 'omit-xml-declaration':true()})"/>
        
        <!-- 统计&的实体引用&的出现次数 -->
        <xsl:variable name="amp-count" select="count(tokenize($p-markup, '&amp;amp;')) - 1"/>
        <!-- 统计"的实体引用"的出现次数 -->
        <xsl:variable name="quot-count" select="count(tokenize($p-markup, '&amp;quot;')) - 1"/>
        
        <xsl:text>&amp;出现</xsl:text>
        <xsl:value-of select="$amp-count"/>
        <xsl:text>次,&quot;出现</xsl:text>
        <xsl:value-of select="$quot-count"/>
        <xsl:text>次。</xsl:text>
    </xsl:template>

</xsl:stylesheet>

说明:

  • serialize()将

    的所有子节点(文本、子元素)转换成XML字符串,原XHTML中的&amp;会被序列化为&amp;amp;,&quot;会被序列化为&amp;quot;

  • 用tokenize()按目标子串分割,分割后的片段数量减1即为出现次数

场景2:统计实体对应的实际字符(如&、")

若只需统计解析后的字符出现次数,XSLT 2.0即可实现:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all">

    <xsl:output method="text" encoding="UTF-8"/>

    <xsl:template match="/">
        <!-- 获取所有<p>元素的合并文本内容 -->
        <xsl:variable name="p-text" select="string(//p)"/>
        
        <!-- 统计字符&的出现次数 -->
        <xsl:variable name="amp-count" select="count(tokenize($p-text, '&amp;')) - 1"/>
        <!-- 统计字符"的出现次数 -->
        <xsl:variable name="quot-count" select="count(tokenize($p-text, '&quot;')) - 1"/>
        
        <xsl:text>&amp;出现</xsl:text>
        <xsl:value-of select="$amp-count"/>
        <xsl:text>次,&quot;出现</xsl:text>
        <xsl:value-of select="$quot-count"/>
        <xsl:text>次。</xsl:text>
    </xsl:template>

</xsl:stylesheet>

说明:

  • string(//p)会提取所有

    元素下的文本内容(包括子元素内的文本),自动忽略标签

  • 同样用tokenize()分割统计次数

针对你给出的示例

元素,场景1的执行结果为:&amp;出现1次,&quot;出现2次,符合预期。

内容的提问来源于stack exchange,提问作者ScottD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 10:07:21