RE: Examples of XSLT/XPath

Subject: RE: Examples of XSLT/XPath
From: Mike Brown <mbrown@xxxxxxxxxxxxx>
Date: Tue, 7 Sep 1999 16:10:30 -0600
Stefano Pogliani wrote:
> 	I am looking for some very very simple examples of use
> of XSLT/XPath in which some variables are used (something like
> processing an XML document and producing another XML with the
> grandTotal of some numeric repeated field in the original XML 
> document.

XML output is the default. Elements (within templates) that are not
associated with the XSL namespace (i.e., they don't have the xsl: prefix)
are going to be in your output.

If the field is numeric, use the sum() function -- variables aren't
necessary. The argument to the function is a node-set containing the numbers
to be totaled. Indicate the node-set by using an XPath expression that
identifies the appropriate nodes in the original XML. Here is an example
where this expression is very explicit: '/doc/num' matches element nodes
named 'num' that are children of elements named 'doc' that are children of
the root node.

Given this XML:

<?xml version="1.0"?>
<doc>
    <num>1</num>
    <num>7</num>
    <notnum>hello world</notnum>
    <num>4</num>
</doc>

Here is the simplest XSL that gives you the total of all 'num' element
children of 'doc':

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/XSL/Transform/1.0";>
    <xsl:template match="/">
        <xsl:element name="grandTotal" select="sum(/doc/num)"/>
    </xsl:template>
</xsl:stylesheet>

...This is exactly the same as:

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/XSL/Transform/1.0";>
    <xsl:template match="/">
        <grandTotal><xsl:value-of select="sum(/doc/num)"/></grandTotal>
    </xsl:template>
</xsl:stylesheet>

...And if you really need to use variables:

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/XSL/Transform/1.0";>
    <xsl:template match="/">
        <xsl:variable name="total" select="sum(/doc/num)"/>
        <grandTotal><xsl:value-of select="$total"/></grandTotal>
    </xsl:template>
</xsl:stylesheet>


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


Current Thread