Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's my version. I've tested it over your XML sample and it works.</p> <p>To invoke it, use <code>&lt;xsl:apply-templates select="path/to/body/*" mode="truncate"/&gt;</code>.</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:strip-space elements="*"/&gt; &lt;!-- limit: the truncation limit --&gt; &lt;xsl:variable name="limit" select="250"/&gt; &lt;!-- t: Total number of characters in the set --&gt; &lt;xsl:variable name="t" select="string-length(normalize-space(//body))"/&gt; &lt;xsl:template match="*" mode="truncate"&gt; &lt;xsl:variable name="preceding-strings"&gt; &lt;xsl:copy-of select="preceding::text()[ancestor::body]"/&gt; &lt;/xsl:variable&gt; &lt;!-- p: number of characters up to the current node --&gt; &lt;xsl:variable name="p" select="string-length(normalize-space($preceding-strings))"/&gt; &lt;xsl:if test="$p &amp;lt; $limit"&gt; &lt;xsl:element name="{name()}"&gt; &lt;xsl:apply-templates select="@*" mode="truncate"/&gt; &lt;xsl:apply-templates mode="truncate"/&gt; &lt;/xsl:element&gt; &lt;/xsl:if&gt; &lt;/xsl:template&gt; &lt;xsl:template match="text()" mode="truncate"&gt; &lt;xsl:variable name="preceding-strings"&gt; &lt;xsl:copy-of select="preceding::text()[ancestor::body]"/&gt; &lt;/xsl:variable&gt; &lt;!-- p: number of characters up to the current node --&gt; &lt;xsl:variable name="p" select="string-length(normalize-space($preceding-strings))"/&gt; &lt;!-- c: number of characters including current node --&gt; &lt;xsl:variable name="c" select="$p + string-length(.)"/&gt; &lt;xsl:choose&gt; &lt;xsl:when test="$limit &amp;lt;= $c"&gt; &lt;xsl:value-of select="substring(., 1, ($limit - $p))"/&gt; &lt;xsl:text&gt;&amp;#8230;&lt;/xsl:text&gt; &lt;/xsl:when&gt; &lt;xsl:otherwise&gt; &lt;xsl:value-of select="."/&gt; &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;/xsl:template&gt; &lt;xsl:template match="@*" mode="truncate"&gt; &lt;xsl:attribute name="{name(.)}"&gt;&lt;xsl:value-of select="."/&gt;&lt;/xsl:attribute&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload