使用XSL 2.0/3.0处理时统计<p>元素中特定字符组合的次数
使用XSL 2.0/3.0统计XHTML中
元素内特定字符组合的出现次数
针对你需要统计
元素中&和"这两个实体引用出现次数的需求,分两种场景给出实现方案:
场景1:统计原XHTML标记中的实体引用字符串(如&、")
适用于需要统计原始代码里的实体引用,而非解析后的字符。此方案依赖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;')) - 1"/> <!-- 统计"的实体引用"的出现次数 --> <xsl:variable name="quot-count" select="count(tokenize($p-markup, '&quot;')) - 1"/> <xsl:text>&出现</xsl:text> <xsl:value-of select="$amp-count"/> <xsl:text>次,"出现</xsl:text> <xsl:value-of select="$quot-count"/> <xsl:text>次。</xsl:text> </xsl:template> </xsl:stylesheet>
说明:
serialize()将的所有子节点(文本、子元素)转换成XML字符串,原XHTML中的
&会被序列化为&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, '&')) - 1"/> <!-- 统计字符"的出现次数 --> <xsl:variable name="quot-count" select="count(tokenize($p-text, '"')) - 1"/> <xsl:text>&出现</xsl:text> <xsl:value-of select="$amp-count"/> <xsl:text>次,"出现</xsl:text> <xsl:value-of select="$quot-count"/> <xsl:text>次。</xsl:text> </xsl:template> </xsl:stylesheet>
说明:
string(//p)会提取所有元素下的文本内容(包括子元素内的文本),自动忽略标签
- 同样用
tokenize()分割统计次数
针对你给出的示例
元素,场景1的执行结果为:&出现1次,"出现2次,符合预期。
内容的提问来源于stack exchange,提问作者ScottD
相关产品推荐
相关产品推荐

