需要计算换行符的数量

时间:2012-06-08 13:30:34

标签: xslt break

我正在使用此代码在每150个字符的XML字符串中创建中断。

<xsl:variable name="val_cr_ln" select=" '&#xA;' " />

每次发生这个变量时我都需要计算一次。

有人可以告诉我我会怎么做吗?

由于

2 个答案:

答案 0 :(得分:0)

查找XML文档中特定字符串出现的次数:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:exslstr="http://exslt.org/strings"
>

    <xsl:template match="/">
        <xsl:variable name='xml_as_str'>
            <xsl:apply-templates select='*' />
        </xsl:variable>
        <p>There are <xsl:value-of select='count(exslstr:split($xml_as_str, "string")) - 1' /> occurrences of "string" in there source XML.</p>
    </xsl:template>

</xsl:stylesheet>

可以在这里运行:http://www.xmlplayground.com/7QAvNp

答案 1 :(得分:0)

这是一个XPath单行

string-length(/) - string-length(translate(string(/), $vNL, ''))

这将评估XML文档中所有文本节点串联的NL字符总数

<强>解释

translate(string(/), $vNL, '')从文档节点的字符串值(XML文档中所有文本节点的串联)生成另一个字符串,其中任何NL字符已被空字符串(已删除)替换。

然后,从总字符串长度中减去此值,可以准确地给出(删除的)NL字符的数量

以下是完整的代码示例

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:variable name="vNL" select="'&#x0A;'"/>

 <xsl:template match="/">
  <xsl:value-of select=
  "string-length(/)
  - string-length(translate(string(/), $vNL, ''))
  "/>
 </xsl:template>
</xsl:stylesheet>

将此转换应用于以下XML文档时:

<text>
Dec. 13 — As always for a presidential inaugural, security and surveillance were
extremely tight in Washington, DC, last January. But as George W. Bush prepared to
take the oath of office, security planners installed an extra layer of protection: a
prototype software system to detect a biological attack. The U.S. Department of
Defense, together with regional health and emergency-planning agencies, distributed
a special patient-query sheet to military clinics, civilian hospitals and even aid
stations along the parade route and at the inaugural balls. Software quickly
analyzed complaints of seven key symptoms — from rashes to sore throats — for
patterns that might indicate the early stages of a bio-attack. There was a brief
scare: the system noticed a surge in flulike symptoms at military clinics.
Thankfully, tests confirmed it was just that — the flu.
</text>

产生了想要的正确结果

12