Image

XSLT in 21 Days

Michiel van Otegem

Image
800 East 96th St., Indianapolis, Indiana, 46240 USA

Sams Teach Yourself XSLT in 21 Days

Copyright © 2002 by Sams

Library of Congress Catalog Card Number: 2001094829

Printed in the United States of America

First Printing: February 2002

07        06        05        5        4        3        2

Trademarks

Warning and Disclaimer

ASSOCIATE PUBLISHER

Paul Boger

ACQUISITIONS EDITOR

Rochelle J. Kronzek

DEVELOPMENT EDITOR

Songlin Qiu

MANAGING EDITOR

Matt Purcell

PROJECT EDITOR

Natalie Harris

COPY EDITOR

Chuck Hutchinson

INDEXER

Kelly Castell

PROOFREADER

Kay Hoskin

TECHNICAL EDITOR

Mike Wooding

TEAM COORDINATOR

Pamalee Nelson

INTERIOR DESIGNER

Dan Armstrong

COVER DESIGNER

Alan Clements

PAGE LAYOUT

Stacey Richwine-DeRome
Gloria Schurick

Contents at a Glance

Introduction

WEEK 1 At a Glance

Day 1 Getting Started with XSLT

2  Transforming Your First XML

3  Selecting Data

4  Using Templates

5  Inserting Text and Elements

6  Conditional and Iterative Processing 139

7  Controlling the Output

WEEK 1 In Review

WEEK 2 At a Glance

8  Working with Variables

9  Working with Parameters

10  Understanding Data Types

11  Working with Strings

12  Sorting and Numbering

13  Working with Multifile Stylesheets 319

14  Working with Multiple XML Sources 341

WEEK 2 In Review:

WEEK 3 At a Glance

15  Working with Namespaces

16  Advanced Data Selection

17  Using Recursion

18  Building Computational Stylesheets 441

19  Working with XSLT Extensions

20  Working with Different Processors 485

21  Designing XML and XSLT Applications 507

WEEK 3 In Review

Appendixes

Appendix A  Answers to Quiz Questions and Exercises

 B   A Quick Reference of XSLT Elements and Functions

 C   Command-Line Reference for Selected Processors

 D   XML Resources on the Web

 Index

Contents

Introduction

Who Is This Book’s Intended Audience?

What Do You Need to Know Before You Read This Book?

What Will You Learn from This Book?

What Software Will You Need to Complete the Examples Provided with This Book?

How This Book Is Organized

What’s on the Sams Web Site for This Book

Conventions Used in This Book

WEEK 1 At a Glance

DAY 1 Getting Started with XSLT

Overview of XSLT

Introduction to XML and XSLT

XSLT and the XML Family

The Benefits of XSLT

When Not to Use XSLT

How Does XSLT Work?

XSLT Transformation Explained

Understanding Declarative Programming

Creating XSLT Files

Using a Text Editor

Using an XML Editor

XSLT Editors and Debuggers

XSLT Design Tools

Processors for XML Transformation with XSLT

MSXML

Saxon

Xalan

Summary

Q&A

Workshop

Quiz

Exercise

DAY 2 Transforming Your First XML

Anatomy of a Stylesheet

What Is a Stylesheet?

Basic Stylesheet Elements

Simplified Stylesheet Syntax

Applying a Stylesheet to an XML Source

Linking a Stylesheet to an XML Source

Embedding a Stylesheet in an XML Source

Executing a Stylesheet Using Code

Summary

Q&A

Workshop

Quiz

Exercise

DAY 3 Selecting Data

Understanding the XML Document Tree

What Is a Node?

What Is a Node-Set?

Understanding XPath

Selecting Elements

Selecting Attributes

Beyond the Basics

Summary

Q&A

Workshop

Quiz

Exercise

DAY 4 Using Templates

Understanding Templates

A Closer Look at Templates

The Benefit of Using Templates

Creating and Using Templates

More About Match Templates

Using Named Templates

Determining Which Template Is Used

Different Templates for Different Cases

Template Priorities

Adding Your Own Priorities

Summary

Q&A

Workshop

Quiz

Exercises

DAY 5 Inserting Text and Elements

Inserting Text

Text with Special Characters

Special Characters in XSLT

Inserting Elements and Attributes

Inserting Elements

Inserting Attributes

Copying Elements from the Source Document

Copying Only the Context Node

Copying Node-Sets and Tree Fragments

Inserting Comments and Processing Instructions

Inserting Comments

Inserting Processing Instructions

Summary

Q&A

Workshop

Quiz

Exercise

DAY 6 Conditional and Iterative Processing

Iterating Through a Node-Set

Processing Each Node in a Node-Set

Filtering Node-Sets

Using Node-Set Functions

Conditional Processing

Simple Conditional Processing

Conditional Processing with Multiple Options

More About Expressions

Formalizing Expressions

Using Multiple Predicates

Combining Expressions

Using Boolean Functions

Negating an Expression Result

Conversion to Boolean Values

Summary

Q&A

Workshop

Quiz

Exercises

DAY 7 Controlling the Output

Creating Different Output Formats

Understanding XML Output

Creating HTML Output

Creating Other Types of Output

Specifying the Media Type

Output Encoding and Output Escaping

Determining the Output Encoding

Encoding Characters That Are Not Supported

Disabling Output Escaping

Controlling Whitespace

Understanding Whitespace

Stripping Whitespace from the Source Document

Dealing with Whitespace in the Stylesheet

Indenting

Summary

Q&A

Workshop

Quiz

Exercise

WEEK 1 In Review

Overview of Bonus Project 1

Creating an Article with a Table of Contents

Project Overview

Creating the Article XML

Creating the XSLT Document

WEEK 2 At a Glance

DAY 8 Working with Variables

Understanding Variables

What Are Variables?

What Is the Benefit of Variables?

Creating and Using Variables

Using Simple Variables

Using Complex Variables

Creating Variables from Expressions

Using Variables to Replace an Expression

Using Variables for Out-of-Context Data

Creating Variables from XSLT Elements

Summary

Q&A

Workshop

Quiz

Exercise

DAY 9 Working with Parameters

Understanding Parameters

What Are Parameters?

What Is the Benefit of Parameters?

Using Parameters

Using Parameters to Alter the Output

Using Parameters to Create Template Functions

Getting Data from Outside the Stylesheet

Summary

Q&A

Workshop

Quiz

Exercise

DAY 10 Understanding Data Types

Data Type Basics

What Is a Data Type?

Data Types in XSLT

Conversion Between Data Types

Explicit Data Type Conversion

Implicit Data Type Conversion

Conversion Pitfalls

Comparing Values

Comparison Pitfalls

Summary

Q&A

Workshop

Quiz

Exercise

DAY 11 Working with Strings

Operations on Strings

Gluing Strings Together

Checking for Characters in a String

Getting the Length of a String

Working with Partial Strings

Replacing Parts of a String

Formatting Data

Formatting Numbers

Formatting Date And Time

Formatting Other Data

Summary

Q&A

Workshop

Quiz

Exercises

DAY 12 Sorting and Numbering

Sorting

Using Static Sorting

Using Dynamic Sorting

Numbering

Inserting Numbering

Controlling the Numbering Output

Summary

Q&A

Workshop

Quiz

Exercises

DAY 13 Working with Multifile Stylesheets

Using Multiple Stylesheets

The Benefits of Multiple Files

The Drawbacks of Multiple Files

Including Stylesheets

Duplicate Templates

Duplicate Variables and Parameters

Importing Stylesheets

The Difference Between Including and Importing

How to Import a Stylesheet

Overriding Templates

Import Rules for Other Elements

Summary

Q&A

Workshop

Quiz

Exercise

DAY 14 Working with Multiple XML Sources

Accessing Other XML Sources

Getting Data from an XML Source

Defining Additional Documents Dynamically

Linking Source Documents

Specifying a Different File Location

Accessing the Stylesheet Elements

Multidocument Pros and Cons

Multidocument Pitfalls

Multidocument Best Practices

Summary

Q&A

Workshop

Quiz

Exercises

WEEK 2 In Review

Overview of Bonus Project 2

Creating a Multifile Stylesheet with Parameters

Starting Your Project

Creating the Second Stylesheet

Creating a Stylesheet for All the Data

WEEK 3 At a Glance

DAY 15 Working with Namespaces

Understanding Namespaces

Namespaces Explained

The Benefits of Namespaces

The Drawbacks of Namespaces

Namespaces, DTDs, and Schemas

Processing XML Sources with Namespaces

Getting Namespace Information

Inserting and Removing Namespaces

Inserting Nodes with Namespaces

Changing Namespaces

Removing Namespaces

Summary

Q&A

Workshop

Quiz

Exercise

DAY 16 Advanced Data Selection

More About Expressions

Matching and Selecting Data

Comparing Values

Selecting Distinct Values

Working with Keys

What Is a Key?

Using Keys to Select Data

Working with Unique IDs

Selecting Data with a Unique ID

Inserting Unique IDs

Using Keys and Generated IDs to Select Distinct Values

Summary

Q&A

Workshop

Quiz

Exercise

DAY 17 Using Recursion

Understanding Recursion

What Is Recursion?

Why and When Should You Use Recursion?

The Drawbacks of Recursion

Creating Recursive Templates

Recursion with Single Values

Totaling with Recursion

Summary

Q&A

Workshop

Quiz

Exercises

DAY 18 Building Computational Stylesheets

Computational Stylesheets Explained

What Is a Computational Stylesheet?

When Do I Use a Computational Stylesheet?

Operators and Functions Used in Computations

Operators

Functions

Computational Applications

Ranking Teams in a Competition

String Manipulation

Converting Currencies

Summary

Q&A

Workshop

Quiz

Exercise

DAY 19 Working with XSLT Extensions

Understanding XSLT Extensions

What Are XSLT Extensions?

What Are the Benefits of XSLT Extensions?

The Drawbacks of XSLT Extensions

How Do XSLT Extensions Work?

Using Built-in Extensions

Using Extension Elements

Using Extension Functions

Using Extensions with Other Processors

Creating Your Own Extension Functions

Using Java Functions as Extension Functions

Creating an Extension Function with Script

Summary

Q&A

Workshop

Quiz

Exercises

DAY 20 Working with Different Processors

Targeting Multiple Processors

Key Processor Differences

Dealing with Processor Differences

Dealing with Different XSLT Versions

XML Capabilities of Database Servers

Getting and Transforming XML Data with Oracle

Getting XML Data from Microsoft SQL Server

Summary

Q&A

Workshop

Quiz

Exercise

DAY 21 Designing XML and XSLT Applications

Designing XML

XML Design Considerations

Design Tools

Designing XSLT

XSLT Design Considerations

XSLT Design Do’s and Don’ts

Summary

Q&A

Workshop

Quiz

Exercise

WEEK 3 In Review

Overview of Bonus Project 3

Creating a Shopping Basket in XSLT

The Product Data

The Shopping Basket

Displaying the Data

Updating the Basket

Invoking the Processor

Appendixes

A  Answers to Quiz Questions and Exercises

Answers for Day 1

Answers to Quiz Questions

Solution to Exercise

Answers for Day 2

Answers to Quiz Questions

Solution to Exercise

Answers for Day 3

Answers to Quiz Questions

Solution to Exercise

Answers for Day 4

Answers to Quiz Questions

Solutions to Exercises

Answers for Day 5

Answers to Quiz Questions

Solution to Exercise

Answers for Day 6

Answers to Quiz Questions

Solutions to Exercises

Answers for Day 7

Answers to Quiz Questions

Solution to Exercise

Answers for Day 8

Answers to Quiz Questions

Solution to Exercise

Answers for Day 9

Answers to Quiz Questions

Solution to Exercise

Answers for Day 10

Answers to Quiz Questions

Solution to Exercise

Answers for Day 11

Answers to Quiz Questions

Solutions to Exercises

Answers for Day 12

Answers to Quiz Questions

Solutions to Exercises

Answers for Day 13

Answers to Quiz Questions

Solution to Exercise

Answers for Day 14

Answers to Quiz Questions

Solutions to Exercises

Answers for Day 15

Answers to Quiz Questions

Solution to Exercise

Answers for Day 16

Answers to Quiz Questions

Solution to Exercise

Answers for Day 21

Answers to Quiz Questions

Solutions to Exercises

Answers for Day 18

Answers to Quiz Questions

Solution to Exercise

Answers for Day 19

Answers to Quiz Questions

Solutions to Exercises

Answers for Day 20

Answers to Quiz Questions

Solution to Exercise

Answers for Day 21

Answers to Quiz Questions

Solution to Exercise

B  A Quick Reference of XSLT Elements and Functions

XSLT Element Reference

xsl:apply-imports

xsl:apply-templates

xsl:attribute

xsl:attribute-set

xsl:call-template

xsl:choose

xsl:comment

xsl:copy

xsl:copy-of

xsl:decimal-format

xsl:element

xsl:fallback

xsl:for-each

xsl:if

xsl:import

xsl:include

xsl:key

xsl:message

xsl:namespace-alias

xsl:number

xsl:otherwise

xsl:output

xsl:param

xsl:preserve-space

xsl:processing-instruction

xsl:sort

xsl:strip-space

xsl:stylesheet

xsl:template

xsl:text

xsl:transform

xsl:value-of

xsl:variable

xsl:when

xsl:with-param

XSLT and XPath Function Reference

boolean ()

ceiling ()

concat ()

contains ()

count ()

current ()

document ()

element-available ()

false ()

floor ()

format-number ()

function-available ()

generate-id ()

id ()

key ()

lang ()

last ()

local-name ()

name ()

namespace-uri ()

normalize-space ()

not ()

number ()

position ()

round ()

starts-with ()

string ()

string-length ()

substring ()

substring-after ()

substring-before ()

sum ()

system-property ()

translate ()

true ()

unparsed-entity-uri ()

C  Command-Line Reference for Selected Processors

MSXSL

Usage

Options

Saxon

Usage

Options

Xalan

Usage

Options

D  XML Resources on the Web

Index

About the Author

MICHIEL VAN OTEGEM lives and works in the Netherlands. He is the co-founder and Chief Web development Teacher of ASPNL, a consulting and teaching firm targeting the Dutch and European market. He teaches advanced ASP, ASP.NET, and XML/XSLT classes, and writes articles and tutorials for magazines and Web sites, such as ASPNL.com, TopXML.com, ASPAlliance.com, CoDe Magazine, and asp.netPRO magazine. He has had a passion for programming ever since he wrote his first programs in MSX Basic and Z80 assembler, at age 10. Now, nearly two decades later, he is a pioneer in Web development, quick to embrace technologies such as XML and ASP (.NET). He has worked with a wide range of languages and platforms, including ASP (.NET), Visual Basic, Access/SQL Server, C/C++, CGI/Perl, PHP, and, of course, XML and XSLT. He is a long-time contributing member of ASPFriends.com mailing lists, which he now helps to moderate and improve as a valued ASP Ace member.

Dedication

To the love of my life, Annette, for her patience, understanding, and support, and to my parents for their unconditional support and wisdom.

Acknowledgments

This book would not have been possible if my partner, Annette, had not run the house during my mental absence needed to write this book. It would also never have been possible if my parents had not told me to follow my dreams, not to mention that they taught me most of what I know about writing and teaching.

I would have never come into a position to write this book if it weren’t for my valuable friends Andreas Kviby and Charles Carroll, who showed me that I could do more than development work alone. In addition, the encouragement and insights of Peter Vogel (and his lovely wife), Kurt Cagle, Michael Corning, and many other speakers and writers made this work interesting and fun.

I would also like to thank the people at Sams Publishing, specifically Songlin Qiu for dealing with all my issues, Natalie Harris for her quickness, Chuck Hutchinson for his fabulous copy edits, and Shelley Kronzek for her belief in me as an author. A special thanks to Mike Wooding, whose technical comments and humor were of enormous value.

Finally, I would like to thank Steely Dan for creating great music that helped me during the writing process.

Tell Us What You Think!

As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way.

As an Associate Publisher for Sams, I welcome your comments. You can fax, e-mail, or write me directly to let me know what you did or didn’t like about this book—as well as what we can do to make our books stronger.

Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message.

When you write, please be sure to include this book’s title and author as well as your name and phone or fax number. I will carefully review your comments and share them with the author and editors who worked on the book.

Fax:

317-581-4770

E-mail:

[email protected]

Mail:

Paul Boger

 

Sams

 

201 West 103rd Street

 

Indianapolis, IN 46290 USA

Introduction

XML is one of the biggest things to hit the World Wide Web since the invention of the Web itself. It has the simplicity of HTML, looking much like it, but at the same time it is much more powerful. This power comes from its generic nature, which makes XML useful for a myriad of applications, not just on the Web, but in any (distributed) computing environment.

If you want to manipulate XML, you have several choices. By far the most powerful is XSLT, which enables you to do very powerful things with the data stored in an XML document. What makes XSLT so interesting is that it is remarkably simple, but at the same time very powerful. Operations that require many lines of code with conventional techniques can be solved in XSLT with just a few lines of code because XSLT uses a completely different programming paradigm, one that you’ll learn to love during the course of reading this book.

XSLT doesn’t replace existing programming languages, but rather complements them. In that sense, XSLT is just another tool in your toolbox. However, applications that target XML- and XSLT-enabled Web browsers, such as Internet Explorer, don’t need any additional programming. This means you can create distributed applications with little effort.

Finally, because XML and XSLT are World Wide Web Consortium–endorsed standards, they are truly cross-platform. Any platform equipped with an XSLT processor can run your application.

Who Is This Book’s Intended Audience?

This book is intended to teach absolute beginners the basics of XSLT and much, much more. This means that this book is also suitable for people with basic knowledge and experience with XSLT, because many of the topics are covered in great detail. In addition, the more advanced topics haven’t been forgotten.

What Do You Need to Know Before You Read This Book?

This book starts at the very beginning of XSLT, so you don’t need any prior knowledge of XSLT. Because XSLT operates on and is itself XML, you need a basic knowledge of XML. This means you need to know what XML is, what its syntax is, and how it is structured. Beyond that, you really don’t need anything else. Having a working knowledge of HTML does help, however. Any prior programming experience is not required; in fact, XSLT programming is based on another programming paradigm than that used in languages such as C++, Java, and Visual Basic. Any prior programming experience is therefore of limited use.

What Will You Learn from This Book?

This book will teach you anything you need to know about XSLT as a programming language. You will learn how to create XSLT documents and how to use them to transform XML documents to text, HTML, or other XML formats. You also will learn how to use processors to apply XSLT to XML documents and how to use data that is not in the XML document. After you finish the book, you will be able to create complex XSLT documents performing complex transformations of XML documents.

What Software Will You Need to Complete the Examples Provided with This Book?

To complete the samples in the book, you need a text editor and an XSLT processor. Unless otherwise specified, the processor used in this book is Saxon version 6.2.2. Other processors discussed are Xalan Java and Microsoft’s MSXML parser/processor component, complemented by the MSXSL command-line tool for this component. You can find information about these processors, including download locations, in Appendix C. At http://xml.startkabel.nl/, you can find links to most processors available, most of which are free.

How This Book Is Organized

This book is organized so you learn XSLT in 21 days. Therefore, there are 21 lessons, one lesson for each of the 21 days. The lessons are grouped in equal parts of seven lessons, so one part corresponds to one week. Each week concludes with a Bonus Project, which creates an application from scratch, based on the topics covered in that week. This book also contains several appendixes.

Week 1 aims to build your basic knowledge of XSLT. You will learn about processors, editors, and most importantly, about the structure and elements in XSLT. After completing week 1, you will have a good working knowledge to create basic XSLT documents.

Week 2 extends your knowledge of XSLT, based on what you learned in week 1. In this week, you will learn about the more intricate details of XSLT and how to create more complex and flexible documents. You also will learn how to create applications that span multiple documents.

Week 3 discusses a myriad of different topics that go beyond day-to-day use of XSLT, such as performing computations with XSLT and using processor-specific constructs. The last day also looks back at all that you have learned from an application design point of view, which will help you to design and implement your applications to be flexible and more robust.

This book includes four appendixes:

Appendix A contains the answers to the questions and exercises in the book.

Appendix B contains a quick reference to all elements and functions in XSLT.

Appendix C contains information and a command-line reference on MSXSL, Saxon, and Xalan Java.

Appendix D contains a list of useful XML and XSLT resources on the Web.

What’s on the Sams Web Site for This Book

The chapter-by-chapter code files described in this book are available on the Sams Web site at http://www.samspublishing.com/. Enter this book’s ISBN in the Search box and click Search. When the book’s title is displayed, click the title to go to a page where you can download all the code in a chapter-by-chapter zip file format.

Conventions Used in This Book

The following typographic conventions are used in this book:

• Code lines, commands, statements, variables, and any text you type or see onscreen appear in a mono typeface. Bold mono typeface is used to represent the user’s input.

• Placeholders in syntax descriptions appear in an italic mono typeface. Replace the placeholder with the actual filename, parameter, or whatever element it represents.

NEW TERM

Italics highlight technical terms when they’re being defined. A paragraph that defines technical terms is marked by an icon.

• The Image icon is used before a line of code that is really a continuation of the preceding line. Sometimes a line of code is too long to fit as a single line on the page. If you see Image before a line of code, remember that it’s part of the line immediately above it.

OUTPUT

• Code listings that show output are marked with an output icon.

• The book also contains Notes, Tips, and Cautions to help you spot important or useful information more quickly. Some of them are helpful shortcuts to help you work more efficiently.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.212.124