XSLT For Dummies®
Published by
Wiley Publishing, Inc.
111 River St.
Hoboken, NJ 07030-5774
www.wiley.com
Copyright © 2002 Hungry Minds, Inc. All rights reserved. No part of this book, including interior design, cover design, and icons, may be reproduced or transmitted in any form, by any means (electronic, photocopying, recording, or otherwise) without the prior written permission of the publisher.
Library of Congress Control Number: 2002100181
ISBN: 0-7645-3651-6
Printed in the United States of America
10 9 8 7 6 5 4 3 2 1
1O/RR/QT/QS/IN
Distributed in the United States by Hungry Minds, Inc.
Distributed by CDG Books Canada Inc. for Canada; by Transworld Publishers Limited in the United Kingdom; by IDG Norge Books for Norway; by IDG Sweden Books for Sweden; by IDG Books Australia Publishing Corporation Pty. Ltd. for Australia and New Zealand; by TransQuest Publishers Pte Ltd. for Singapore, Malaysia, Thailand, Indonesia, and Hong Kong; by Gotop Information Inc. for Taiwan; by ICG Muse, Inc. for Japan; by Intersoft for South Africa; by Eyrolles for France; by International Thomson Publishing for Germany, Austria and Switzerland; by Distribuidora Cuspide for Argentina; by LR International for Brazil; by Galileo Libros for Chile; by Ediciones ZETA S.C.R. Ltda. for Peru; by WS Computer Publishing Corporation, Inc., for the Philippines; by Contemporanea de Ediciones for Venezuela; by Express Computer Distributors for the Caribbean and West Indies; by Micronesia Media Distributor, Inc. for Micronesia; by Chips Computadoras S.A. de C.V. for Mexico; by Editorial Norma de Panama S.A. for Panama; by American Bookshops for Finland.
For general information on Hungry Minds’ products and services please contact our Customer Care Department within the U.S. at 800-762-2974, outside the U.S. at 317-572-3993 or fax 317-572-4002.
For sales inquiries and reseller information, including discounts, premium and bulk quantity sales, and foreign-language translations, please contact our Customer Care Department at 800-434-3422, fax 317-572-4002, or write to Hungry Minds, Inc., Attn: Customer Care Department, 10475 Crosspoint Boulevard, Indianapolis, IN 46256.
For information on licensing foreign or domestic rights, please contact our Sub-Rights Customer Care Department at 212-884-5000.
For information on using Hungry Minds’ products and services in the classroom or for ordering examination copies, please contact our Educational Sales Department at 800-434-2086 or fax 317-572-4005.
For press review copies, author interviews, or other publicity information, please contact our Public Relations Department at 317-572-3168 or fax 317-572-4168.
For authorization to photocopy items for corporate, personal, or educational use, please contact Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, or fax 978-750-4470.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND AUTHOR HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK. THE PUBLISHER AND AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. THERE ARE NO WARRANTIES THAT EXTEND BEYOND THE DESCRIPTIONS CONTAINED IN THIS PARAGRAPH. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS. THE ACCURACY AND COMPLETENESS OF THE INFORMATION PROVIDED HEREIN AND THE OPINIONS STATED HEREIN ARE NOT GUARANTEED OR WARRANTED TO PRODUCE ANY PARTICULAR RESULTS, AND THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY INDIVIDUAL. NEITHER THE PUBLISHER NOR AUTHOR SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER DAMAGES.
Trademarks: Hungry Minds, the Hungry Minds logo, For Dummies, the Dummies Man logo, A Reference for the Rest of Us!, The Fun and Easy Way, The Dummies Way, Hungry Minds a la Carte and related trade dress are trademarks or registered trademarks of Hungry Minds in the United States and other countries and may not be used without written permission. All other trademarks are the property of their respective owners. Hungry Minds, Inc. is not associated with any product or vendor mentioned in this book.
Richard Wagner is vice president of Development Tools at Nombas, a JavaScript tools provider, and author of numerous books, including JavaScript Unleashed. He also invented and architected the award-winning NetObjects ScriptBuilder and served as editor for the XML-based ECMAScript Components standard. In his free time, he enjoys writing on his nontech Web site called digitalwalk.net (www.digitalwalk.net). Rich lives with his wife and three boys in Princeton, Massachusetts. He can be reached at rich@digitalwalk.net.
To the intrepid J-boys — Jordan, Jared, and Justus. In all things, “to the hilt . . .”
In writing this book, I was blessed with an unbeatable editorial team at Hungry Minds. My deepest thanks go to Christine Berman for her flawless management of this project from start to finish. Thanks to Becky Huehls for her keen editing eye and helpful suggestions, driving me to be clearer and more concise in my writing. Thanks also to Bob Dominy for his technical insights that made a strong impact on the book’s overall quality and coverage. I talk about the X-Team in this book, but I’d say the book’s X-Factor is Christine, Becky, and Bob. For without them, XSLT For Dummies would have been far less of a book.
I’d also like to express thanks to Steven Hayes at Hungry Minds for his involvement early on in the project, as well as thank my agent, Chris Van Buren.
Finally, I’d like to express earnest gratitude to my wife, Kimberly, and our three boys, the J-team, for their patience and grace throughout the entire project.
We’re proud of this book; please send us your comments through our Hungry Minds Online Registration Form located at www.dummies.com.
Some of the people who helped bring this book to market include the following:
Acquisitions, Editorial, and Media Development
Associate Project Editor: Christine Berman
Senior Acquisitions Editor: Steve Hayes
Copy Editor: Rebecca Huehls
Technical Editor: Robert Dominy
Editorial Manager: Leah Cameron
Media Development Manager: Laura VanWinkle
Media Development Supervisor: Richard Graves
Editorial Assistant: Amanda Foxworth
Production
Project Coordinator: Maridee Ennis
Layout and Graphics: Jackie Nicholas, Barry Offringa, Heather Pope, Jacque Schneider, Betty Schulte, Mary J. Virgin, Erin Zeltner
Proofreaders: John Greenough, Andy Hollandbeck, Susan Moritz, Angel Perez, TECHBOOKS Production Services
Indexer: TECHBOOKS Production Services
General and Administrative
Hungry Minds Technology Publishing Group: Richard Swadley, Vice President and Executive Group Publisher; Bob Ipsen, Vice President and Group Publisher; Joseph Wikert, Vice President and Publisher; Barry Pruett, Vice President and Publisher; Mary Bednarek, Editorial Director; Mary C. Corder, Editorial Director; Andy Cummings, Editorial Director
Hungry Minds Manufacturing: Ivor Parker, Vice President, Manufacturing
Hungry Minds Marketing: John Helmus, Assistant Vice President, Director of Marketing
Hungry Minds Production for Branded Press: Debbie Stailey, Production Director
Hungry Minds Sales: Michael Violano, Vice President, International Sales and Sub Rights
Title
Introduction
What I Assume About You
How This Book Is Organized
Conventions Used in This Book
Icons Used in This Book
Part I : Getting Started with XSLT
Chapter 1: Introducing the X-Team
XML: Storing Your Data
XSL: Presenting XML Data
XSLT: Transforming Your XML Data
XPath: Seeking Out Your Data
The X-Team through HTML Eyes
Chapter 2: Writing Your First XSLT Stylesheet
Preparing Your XSLT Working Environment
Creating a Simple XML Document
Knowing the End Result
Writing an XSLT Stylesheet
Processing the Stylesheet
Viewing the Results
Part II : Becoming an XSLT Transformer
Chapter 3: Transforming with Style (Stylesheets, That Is)
Structure of a Stylesheet
Constructing Your XSLT Stylesheet
What’s in a Name(space)?
Documents as Trees
Chapter 4: Templates Rule!
A Glorified Mail Merge
Basics of a Template Rule
Common Action Instructions
Built-In Template Rules
Matchmaker, Make Me a Match
Working with Attribute Value Templates
Working with Named Templates
Chapter 5: XPath Espresso
XPath, The X-Team’s Commando
Dancing the Location Step
Defining Relationships with Axes
Matching Nodes with Node Tests
Using Predicates to Get Specific
Take a Walk on the Absolute Side
Putting It All Together
Chapter 6: We Want Results!
XSLT, Like Skinning a Cat
XML Source
Copying an Element
Copying All Elements
Adding a New Element
Adding a Calculated Value
Renaming an Element
Removing an Element
Removing an Attribute
Reordering Elements
Merging Elements
Adding Attributes
Moving an Attribute
Converting Elements into Attributes
Converting Attributes into Elements
Part III : Prime Time XSLT
Chapter 7: Adding Programming Logic Isn’t Just for Propheads
Conditional and Looping Statements
If and Only If
Testing Expressions with Logical Operators
Why Choosy People Choose xsl:choose
Going Loopy with xsl:for-each
Chapter 8: Variables in XSLT: A Breed Apart
What Is a Variable?
Setting Variables
Uses of Variables
Think Globally, Act Locally
Working with Parameters
Chapter 9: Tweaking the Results to Get What You Want
Sorting Elements in the Results Tree
Adding Automatic Numbering
Chapter 10: To HTML and Beyond!
XML and HTML
Outputting to HTML
Creating an HTML Table
Linking an XSLT Stylesheet with an XML Document
Browser Support of XSLT
To Infinity and Beyond (Into Other Formats)
Chapter 11: XPath Data Types and Functions
Playing ‘Heart and Soul’ with Nodes
Working with Strings
Numerically Speaking
Booleans: To Be or Not to Be
General Purpose Functions
Part IV : eXtreme XSLT
Chapter 12: Combining XSLT Stylesheets
Comparing xsl:include and xsl:import
Practical Use of xsl:import
Chapter 13: “Gimme Some Space” and Other Output Issues
Gimme Some Space
Indenting Your Result Document
Adding Comments
Adding Processing Instructions
Chapter 14: Keys and Cross-Referencing
Keys to the Kingdom
Using Keys with Multiple Source Documents
Chapter 15: Namespaces Revisited
Speaking the Namespace Lingo
Adding a Namespace to the Result Document
Working with Multiple Namespaces
Chapter 16: Extending XSLT
Going Beyond the Basics
Using an Extension Element
Using an Extension Function
Ensuring Portability of Your Stylesheets
Chapter 17: Debugging XSLT Transformations
Conditionally Halting Execution
Adding a Conditional Debug Mode
Tracing through Your Code
More Powerful Debugging
Part V : The Part of Tens
Chapter 18: Ten Most Confusing Things About XSLT
Built-In Template: The Man Behind the Screen
Thar’s Trees in Them Documents
Getting to the Root of the Issue
Why the Selected Node Is Not the Same as the Current Node
Those //@.}* Abbreviations
To Apply or Copy, That Is the Question
Walk This Way
Expressions, Paths, and Steps
Those Cute Little Curly Braces
Whitespace, the Final Frontier
Chapter 19: Ten All-Pro XSLT Resources on the Web
Xslt.com
W3C XSLT Recommendation
W3C XPath Recommendation
Dave Pawson’s XSLT FAQ
W3School’s XSL School
MSDN’s XML Center
Xml101.com
Jeni’s XSLT Pages
TopXML: XSLT Reference
Nic Miloslav’s XSLT Tutorial
Chapter 20: Ten XSLT Processors Available Online
Saxon
msxsl
Sablotron
Xalan-C++
Xalan-Java
LotusXSL
XT
jd.xslt
XML::XSLT
libxslt
Glossary
Everyone seems to be talking about Extensible Markup Language (XML) these days. You know how mothers are — I can’t even visit my relatives over the holidays without my mom broaching the topic of XML at Thanksgiving dinner. Yes, XML has become quite a buzzword, but Extensible Stylesheet Language Transformations (XSLT) is the power that takes all this XML and turns it into something useful and flexible.
XSLT is a language used to transform XML documents into something new. It can take one XML document and output that document’s information into a completely different structure or turn XML into an HTML document for viewing on the Web. XSLT isn’t a general-purpose programming language, such as Java or Visual Basic; its focus is solely on transforming XML.
Before I get any farther along, I have to point out the “elephant in the room” — XSLT’s long-winded name. Who came up with that name anyway? I think the people responsible should be forced to say, “Extensible Stylesheet Language Transformations,” aloud ten times and hope their tongues don’t fall off! XSLT’s full name may be a mouthful, but this book carves up each piece of XSLT into manageable, chewable morsels.
XSLT can be confusing if you don’t have a solid understanding of its syntax, quirky abbreviations, and the esoteric terminology it sometimes uses. But XSLT For Dummies can help you write XSLT stylesheets and, just as important, grasp why and how transformations work. In addition, see www.dummies.com/extras/xsltfd for code examples as well as a helpful editing tool of my own creation which I call the X-Factor.
Above all, you can use XSLT For Dummies as your guide for quickly developing the know-how of XSLT — without drowning in technical gobbledygook.
XSLT For Dummies starts from the bottom and works its way up: It doesn’t assume that you have any previous knowledge of XSLT or XML. If you have some know-how of HTML or programming, I think you can grasp some of the concepts of XSLT quicker than a beginner, but I don’t expect you to know HTML or anything about programming beforehand.
My aim is to help you find out how to become productive with XSLT quickly so that you can transform XML documents into virtually any kind of output imaginable. With that goal in mind, XSLT For Dummies is divided into five parts, each of which builds upon the previous ones.
Part I kicks off your journey. You start by finding out about the core concepts of XSLT and how it fits in with HTML and all the other X technologies out there, such as XML, XSL, and XPath. You get your feet wet by writing your first XSLT stylesheet and transforming an XML document.
After you finish that, you can say XSLT to your buddies at work and actually have a grasp of what you’re talking about when you throw around those X terms.
This part takes you into the belly of the beast: stylesheets, template rules, and XPath expressions. But don’t worry — you won’t lose your appetite. You begin by looking at stylesheets and find out, in everyday terms, the often-confusing subject of document trees and recursion. From there, you start pulling information out of XML documents and outputting it into various forms.
By the time you’re done with this part, you’ll be able to say, “Extensible Stylesheet Language Transformations,” without stumbling over any of the twelve syllables.
In this part, you dive deeper into the thick of things. You find out how XSLT handles programming concepts such as if/then statements, loops, and variables, and how to include them in stylesheets. Don’t worry if you’ve never programmed before; these concepts become clear as you read through the chapters. You also find out about how to take advantage of the more advanced capabilities of XSLT and XPath to create more powerful transformations.
I predict that after you finish this part, at least once you’ll have unintentionally ordered an XSLT sandwich on rye at your local deli.
As you read through Part IV, you can begin to call yourself a bona fide XSLT Transformer. You find out how to create effective XSLT stylesheets and apply them under various conditions. You find out about how to combine stylesheets and even add your own extensions. You also get the inside scoop on debugging transformations.
A word of warning: By now, all this XSLT will be swimming around in your head. You may find yourself mingling at a social event and leading with the line: “Apply any good templates lately?”
In this part, I guide you through some practical tips and information that can make your life easier when you work with XSLT. I start out by demystifying the ten most confusing things about XSLT. Then I detail what I consider to be the ten best XSLT resources on the Web. I conclude by giving you the details on ten XSLT processors that you can download online.
Snippets of XSLT code are scattered throughout the book and are often used to introduce you to a feature of the markup language. They appear in the chapters like this:
<xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform” version=”1.0”>
<xsl:template match=”id”>
<h1><xsl:apply-templates/></h1>
</xsl:template>
</xsl:stylesheet>
If you type these stylesheets by hand, pay close attention and type the text exactly as shown to ensure that the stylesheet transforms properly. Generally, spaces don’t matter much, although depending on where they are, they could change the look of the output from a transformation. However, case sensitivity is important for any XML or XSLT element. I use lowercase text in all the examples, so I recommend getting used to typing lowercase to avoid confusion or problems down the line.
If XSLT element names or instructions appear within the regular text, they look like this.
In this part . . .
Y ou watched the X-Files and then you saw X-Men on the big screen, but these were only warm-ups for the real deal — the X-Team. In this part, you find out all about the X-Team members, including XML, XSL, XSLT, and XPath, and how they work together. You also get your feet wet by transforming your first XML document using XSLT.