XSLT Tutorial
XPath: Functions cont.
number
The number function converts any value to a number. If the
value being parsed is a string, it will return 'NaN' (not a
number).
The following example examines a node-set which contains a
number:
<p>The number is: <xsl:value-of
select="number(books/book/price)"/></p>
The output:
The number is: 17.49
position
The position() function returns the position value of the element in
its context. Some example of using this function is when you need to insert
numbering next to a list of items, or when you need to test if the
position of element is the last one (which you would test against the
last() function).
If you sort your elements, it will return the
position in its sorted position.
The following example inserts the number next to the book, note we
are using the XSLT element, <xsl:number> in this example:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
<xsl:for-each
select="books/book">
<p><xsl:number value="position()"/>.
<xsl:value-of select="name"/></p>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
The output:
1. XML by Example
2. Professional XML
3. Xml in Action
4. Xml Design and Implementation
5. XML: A Managers Guide
substring
The substring() function returns a part of a string, based on the
parameters you pass to it. The format is:
substring(value, start)
substring(value, start, length)
The character position(start) begins with 1.
In the following example we are selecting the first 3 letters of the
book name:
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<xsl:for-each
select="books/book">
<p><xsl:value-of select="substring(name, 1,
3)"/></p>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
The output:
XML
Pro
Xml
Xml
XML
sum
The sum function calculates totals for a node-set. You need
to be aware of nodes that do not contain values, as this function will
return 'NaN' if one of the items is not numeric (i.e. empty).
You will need to do formatting of your code to overcome this, i.e.
replacing empty values with a 0.
sum(node)
In our XML example, if we wanted to calculate the total of all the
book prices, our code could read:
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<p>Total Price = <xsl:value-of
select="sum(//price)"/></p>
</xsl:template>
</xsl:stylesheet>
The output:
Total Price = 146.41
Conclusion
The above functions are but a few of the functions you can use in
XPath. We will be visiting a few more as we go through more
examples.
In the DOMDocument, these XPath expressions can be used in the
selectSingeNode and selectNodes method for finding a node in the
DOMDocument tree.
For example, the following code is searching for all price
elements, whose book has a child element called publish with a value
of "Wrox".
Set xmlNL = xmlDom.documentElement.selectNodes("/books/book[publish=""Wrox""]/price")
|