Re: [xsl] Number of characters in document

Subject: Re: [xsl] Number of characters in document
From: Mike Brown <mike@xxxxxxxx>
Date: Sun, 17 Dec 2000 11:02:36 -0700 (MST)
David_N_Bertoni@xxxxxxxxx wrote:
> On 17-12-2000, Evyatar_Kafkafi wrote:
> >Question: How do I (inside the XSL stylesheet) get the number of
> characters in the whole XML document (or in a specific node)?
> >

Every type of node has a string-value. See the XPath spec where it
describes each type of node. You can obtain the length of that value
with the string-value() function, also described in the XPath spec.

> >for example, if the XML document is:
> ><A>
> >          <B>
> >                    <C>1</C>
> >          </B>
> >          <B>
> >                    <C>1</C>
> >                    <C>2</C>
> >          </B>
> ></A>
> >
> >the number of characters in node A would be the length of the string
> >"<A><B><C>1</C></B><B><C>1</C><C>2</C></B></A>"
> 
> You can't.  XSLT sees the parsed representation of the XML document, not
> the tagged text, so the '<', '</', '</' and '/>' markup isn't present.

To expand on what David said, the markup is not part of the node. The node
is a logical structure that is implied by the markup. <C>3</C> implies the
logical structure 'an element node named C, that is the parent of a text
node containing the 3 character'. There's no way to count the number of
markup characters that were used to produce that logical structure. You
can count the number of characters in the text node if you wanted (there's
just 1 in this example).

But where there's a will, there's a way. *If* you know the name of
the file and you don't mind hard-coding it in your stylesheet, you can
make the file be a general entity which you can refer to in a variable
assignment, and then you take the string-length() of the variable.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE xsl:stylesheet [ <!ENTITY xmlfile SYSTEM "file.xml"> ]>
<xsl:stylesheet ...>
...
    <xsl:variable name="xmlFileAsTextNode">&xmlfile;</xsl:variable>
    <xsl:text>The file's length (in characters) is </xsl:text>
    <xsl:value-of select="string-length($xmlFileAsTextNode)"/>
...

Not exactly general-purpose though.

   - Mike
____________________________________________________________________
Mike J. Brown, software engineer at            My XML/XSL resources: 
webb.net in Denver, Colorado, USA              http://skew.org/xml/

 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list


Current Thread