YOUR FEEDBACK
Werner Keil wrote: Java 6 update 10. If I'd be running Apple, I'd probably really drop dead...
AJAXWorld RIA Conference
$300 Savings Expire September 5th. Register Today and SAVE!


2008 East
DIAMOND SPONSOR:
Data Direct
Frontiers in Data Access: The Coming Wave in Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
Intel
Virtualization – Path to Predictive Enterprise
Green Hills
IT Security in a Hostile World
JBoss / freedom oss
Practical SOA Approach
GOLD SPONSORS:
Software AG
The Art & Science of SOA: How Governance Enables Adoption
PlateSpin
Effective Planning for Virtual Infrastructure Growth
Fujitsu
Automated Business Process Discovery & Virtualization Service
Ceedo
Workspace Virtualization
Click For 2007 West
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
TODAY'S TOP SOA & WEBSERVICES LINKS


XSL 101: XSL Functionality
XSL 101: XSL Functionality

In my last article, "Two Great Technologies, One Amazing Solution" (XML-J, Vol. 2, issue 1), I demonstrated how the Java programming language could be used within stylesheets to add robustness to XSLT. This month I'll stick strictly within the confines of the XPath and XSLT to show some of the built-in functionality available to you.

The XPath and XSLT specifications include sections defining "functions." Whether they're core (required by an implementation of the spec) or external (core extensions or user defined), functions assist the stylesheet writer by providing valuable services such as node value formatting and node set metainformation. In this article I'll explain some of the general syntax rules for using functions and provide examples of the more common types.

This article assumes you have a basic knowledge of XSLT and XSL stylesheets. It's also assumed that those who want to try the examples have a suitable XSLT execution environment, such as Apache Xalan.

W3C Specifications
Functions are mentioned variously within the XPath (www.w3c.org/TR/ xpath.html) and XSLT (www.w3.org/TR/xslt.html) specifications. Although the specifications were written primarily for those wanting to create an implementation (i.e., Xalan), stylesheet writers can also gain from reading them. The general function format is mentioned in the XPath specification (section 3.2):

FunctionCall ::= FunctionName'('(Argument(','Argument)*)?')'
Argument ::= Expr

FunctionCall is identified by its FunctionName and can contain (optional comma-separated) Arguments that are Expr(essions). Basically, this means that functions have predefined names, return single values, and can have arguments that are one of the four XSL object types: node-set, Boolean, number, and string.

If more than one argument is required, they must be comma-separated. Also, arguments are automatically converted to the proper data type, if possible. For example, if the argument is a number and the node value provided is the string "50," that string is converted to a number. It's a problem if the argument can't be converted or if you supply the wrong number of arguments when calling a function.

Functions are generally used within selection statements to either manipulate (not alter) the value of the element or add robustness to the selection criteria. For example, if I wanted to convert the value of a node selection to a number, I could use the number function as follows:

<xsl:value-of select="number(ANUMBER)"/>
This XSL would convert the element "ANUMBER" to a number. If the value of the element isn't a number, an error will occur. Similarly, I could use the position function to match every instance of a particular element except the first, as follows:
<xsl:template match="STUFF[position() > 1]"/>
This would limit the node-set match of "STUFF" by matching elements that have a position (with respect to all "STUFF" elements) greater than 1 (the first occurrence).

Types of Functions
Table 1 is a summary of some of the built-in functions (by category) listed in the XPath and XSLT specifications. I've included the prototype, or general syntax, for each. Note: "?" indicates an optional argument, and "*" indicates zero or more arguments.

Now that you have a basic backdrop, I'll show more concrete examples of some of the functions listed in Table 1. For functions without concrete examples, I recommend checking the specification before using them, since some functions may produce unexpected results.

For the sake of simplicity, I'll use the same XML (see Listing 1) and XSL (see Listing 2) documents to demonstrate all the functions covered.

The number count(node-set) Function

The count function will return a number representing the total number of nodes in the node-set supplied as an argument. This function has many uses, such as determining the total number of items within an invoice:

<xsl:value-of select="count(//ITEM)"/>
This will output the total ITEM elements contained within the source XML document (see Listing 1).

The number sum(node-set) Function

The sum function has a particular usefulness: incremental addition. Al- though you can use the mathematical "+" operator within stylesheets, you can't modify the value of a variable for the purpose of adding together several elements. This is because the specification doesn't allow for the modification of "variables." The implication is that you can't simply navigate through a node-set and increment a "sum" as you go. The good news is that the sum function will do this for you. The only real "trick" is to use XPath to select the correct nodes to pass as the node-set argument.

Let's say I wanted to generate a grand total for all the items within an invoice (again, see Listing 1). The sum function makes this simple, as demonstrated with the following snippet taken from Listing 2:

<xsl:value-of select="sum(//PRICE)"/>
The result is 314.96000000000004. It works, but the format is probably inappropriate for display in a Web page. If only there were a way to format that number...

The string format-number(number, string, string?) Function

This function will take the number argument and format it using the format pattern supplied as the second argument. If you want to create a decimal format other than the default (I guess this would be an uncommon situation), you can (optionally) supply the QName (see the specification for clarification) of another as the third argument. Not providing a third argument implies that you've chosen to use the default provided by the processor implementation. The result is a formatted string.

The format-number function has its roots in Java. Specifically, the format pattern (second argument) is based on the Java Development Kit (JDK) version 1.1 DecimalFormat class. Borrowing the structure from page 459 of Michael Kay's XSLT Programmer's Reference, I provided some examples of valid formats in Table 2.

Notice how the last two patterns provide for both positive and negative number formats. This can be particularly helpful and avoid conditional logic within your stylesheets. Imagine conditionally checking for negative values and appending "CR" at the end. For example:

<xsl:variable name="foo"
select="sum(//PRICE)"/>
<xsl:choose>
<xsl:when test="$foo >= 0">
<xsl:value-of select="$foo"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$foo"/>CR
</xsl:otherwise>
</xsl:choose>

That's a lot of XSL for something so easily handled with the format-number. That would be crazy. Okay, so I've done that before, but only because I didn't want you to have to.

Seriously, though, as an example of format-number, I'll format the result of the sum shown in the previous section. What I'm doing is chaining the functions together. Just like mathematics and programming languages, functional expressions are evaluated from the inner parenthesis out. Therefore:

<xsl:value-of select="format-number(sum(//PRICE), '$#,##0.00')"/>
will first compute the sum, then apply the format. In other words the sum function is executed first (inner parenthesis), then the format-number function (outer parenthesis). The result is a nicely formatted $314.96. Imagine doing that without the format-number. No, I haven't done that too!

The string concat(string, string, string*) Function

The concat function simply returns the concatenation of the string arguments. The first two strings are required, with the last being present zero or more times. This means you can supply any number (greater than or equal to two) of arguments to concat.

In the example, I'll combine the first occurrence of the ID and DESC elements to output a unique identifier for that ITEM. This is done using this concat function:

<xsl:value-of select="concat(//ITEM[1]/ID, //ITEM[1]/DESC)"/>

The result is "S072796Item 1". Listing 3 shows the complete output of transforming the XML in Listing 1 using the XSL stylesheet in Listing 2.

Conclusion
The writers of the XPath and XSLT specifications incorporated a powerful feature in functions. I've demonstrated how functions can be used to format output (format-number), manipulate element values (concat and sum), and provide metainformation about a set of nodes (count). This article has only scratched the surface, so consult the listed resources (or any other XSL resource) to continue your journey into XSL functions.

Resources

About Frank Neugebauer
Frank Neugebauer is a consultant with the Insurance Solutions Group of IBM Global Services. He has been using Java since 1996 and has worked on the architecture and implementation of enterprise Java solutions using Servlets, EJBs, XML, and XSLT. He has also taught Java, HTML, and JavaScript at the University of Michigan Center for Corporate and Professional Development.

YOUR FEEDBACK
What? wrote: "The last time I was this excited about a new SDK was probably when .NET 2.0 came out" OK, that's the funniest thing I think I've ever read in one of these articles. I didn't realize how completely sarcastic it was, but then I imagined Lewis Black reading it out loud and it finally made sense. This whole article is supposed to be a joke. If that's the case, I guess I'll play along: "Needless to say, my hopes and dreams came crumbling down when I realized that this new fangled iPhone device contained an operating system, and if that isn't bad enough, one that was based on some kinda open source garbage - not even windows CE (the nerve!). So I threw the thing out, and promptly started working on SharePoint Unleashed 2nd ed. where at least nobody has the gaul to use an undocumented API. Why are these people doing that? Huh? Why did they have to go and do that? I mean, wait for the...
spinron wrote: Having bought and read the pre-release version of the book discussed here ("Rough-Cuts" edition, available on O'Reilly's site for $20), I tend to disagree with Kevin's opinion and lean more towards the book's author's view that the "unofficial" SDK, or the at least the API represented in it, are likely to more-or-less remain equivalent to the ones that would be exposed by the official Apple iPhone SDK. The iPhone platform implements a subset of the Mac OS X API which the book describes quite nicely. Why on earth would Apple want to re-invent a new API just for the iPhone SDK, after it's worked so hard to perfect its API over a decade? For spite, just to break the existing applications and necessitate a rewrite? Not a strong argument here. Seriously, get the rough-cuts edition now and read it. Consider it a preview for the official SDK. Most of the material it discusses is likely to rema...
Endre Stølsvik wrote: I think this blog entry is stupid. If you're correct, and the book is about jailbroken iPhones, I think it is really cool of O'Reilly to flip the finger at Apple's idiotic attitude. "Confusing the developers" - are you insane or something? Do you believe that you are the only "developer" with more than about 6 brain cells? A "developer" that starts coding on an iPhone without realizing what he's really up against must be fully brain damaged. No, no one will be confuzed. Seriously. ColdFusion Developer's Journal - wow..
germ wrote: Hello? There are a million hacked iPhones out there. Hacking the iPhone is the only reason to buy it.
Brett wrote: Surely they can cater for the reality of iPhone usage in the market ? Hacking the phone and breaking the software license agreement isn't necessarily bad or illegal.. depends who you talk to... There are laws that support the consumer's rights to reverse-engineer their device, or to make changes to allow moving to a different carrier (eg the Digital Millennium Copyright Act). Just because it conflicts with the user's agreement with Apple doesn't make it a 'bad thing', it just means they might have to deal with some contractual consequences, or not...
Pedro wrote: "How many potential developers might stumble upon the information on O'Reilly's site, follow the instructions to start coding, only to eventually realize that customers with unhacked phones can't run their apps??" I think that a person that starts writing code without even notice that it will work only with jailbreaked phones don't have any idea about iphone development and doesn't even deserve the "developer" title.
iPhone News Desk wrote: So is O'Reilly actually condoning the hacking of the phones? O'Reilly has had a long and prestigious history as being the ultimate source for *nix manuals, including many books that became so dogeared I actually bought multiple copies, including dozens of 'in a nutshell' books.
XML JOURNAL LATEST STORIES . . .
To be able to do anything useful, an ESB must be configured with all sorts of parameters, from endpoint connection URIs to message transformation scripts to content-based routing definitions. Moreover, ESBs like Mule can host custom components, which will process messages and perform u...
Representatives of the state IT organizations of Brazil, South Africa and Venezuela, three of the four countries that protested ISO’s standardization of Microsoft’s Office Open XML (OOXML) file format, have apparently thrown in the towel on taking their appeal any further. India, t...
Two of the biggest launches in Rich Internet Application history took place in 2007/2008 when Adobe launched AIR 1.0 in February '08 and Microsoft launched Silverlight (September '07). At the 6th International AJAXWorld RIA Conference & Expo in October SYS-CON Events is delighted to be...
Red Hat CTO Brian Stevens, Citrix CTO Simon Crosby, Egenera CTO Pete Manca, Allen Stewart, Group Manager, Windows Virtualization at Microsoft, and Brian Duckering, Sr. Director of Products and Alliances at Symantec were the top industry executives who joined Jeremy Geelan in the 4th Fl...
This article is aimed at beginner and intermediate Web developers looking to make the leap into database support of their Web site. The article suggests a new declarative language based on HTML-forms, which is used for development of the database interface. HTML forms can manage not on...
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


SYS-CON FEATURED WHITEPAPERS


ADS BY GOOGLE
BREAKING XML NEWS

Security Challenges for the Information Society