Tải bản đầy đủ

Tài liệu Module 4: Displaying an XML Document Using XSL ppt







Contents
Overview 1
Transforming XML with XSL 2
Using Templates 9
Filtering and Sorting XML 22
XSL Language Constructs 33
Creating New Nodes Dynamically 39
Lab 4: Displaying an XML Document Using
XSL 44
Review 52

Module 4: Displaying an
XML Document Using
XSL



Information in this document is subject to change without notice. The names of companies,
products, people, characters, and/or data mentioned herein are fictitious and are in no way intended
to represent any real individual, company, product, or event, unless otherwise noted. Complying
with all applicable copyright laws is the responsibility of the user. No part of this document may
be reproduced or transmitted in any form or by any means, electronic or mechanical, for any
purpose, without the express written permission of Microsoft Corporation. If, however, your only
means of access is electronic, permission to print one copy is hereby granted.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

 2000 Microsoft Corporation. All rights reserved.

Microsoft, PowerPoint, Visual InterDev, and Windows are either registered trademarks or
trademarks of Microsoft Corporation in the U.S.A. and/or other countries.

The names of companies, products, people, characters, and/or data mentioned herein are fictitious
and are in no way intended to represent any real individual, company, product, or event, unless
otherwise noted.

Other product and company names mentioned herein may be the trademarks of their respective
owners.


Program Manager: Steve Merrill
Instructional Designers: Sangeeta Nair (NIIT), Vijayalakshmi Narayanaswamy (NIIT)
Subject Matter Experts: Andy Olsen (QA Training), Andy Longshaw (Content Masters)
Content Lead: Janet Robinson
Graphic Artist: Scott Serna (Creative Assets)
Media Management: David Mahlmann
Media Production: Dean Connolly (Art Source), Timothy Demmon (:timebomb Media)
Editing Manager: Jennifer Linn
Editor: Dennis Rae (Wasser)
Production Manager: Miracle Davis
Print Coordinator: Marlene Lambert (Online Training Solutions, Inc)
Build Manager: Julie Challenger
Build Coordinator: Jenny Boe
Test Lead: Eric Myers
Manufacturing Manager: John Williams
Group Product Manager: Steve Elston


Module 4: Displaying an XML Document Using XSL iii


Instructor Notes
This module describes how to write an XSL style sheet and apply it to a static
XML document. The focus of the module is to describe the syntax for XSL
template rules, and to introduce the various filter and path specifications that
allow you to match particular elements and attributes in an XML document.
Many students find style sheets confusing, partly because there is so much
syntax to learn, but also because the concept of rule-based programming can be
quite alien. The key points to emphasize during the module are that an XSL
document is itself an XML document (with familiar < and > tags), and that a
template rule always has a current context (for example, the element or attribute
that is currently being matched).
The module primarily shows how to transform XML into HTML for display in
a browser. Toward the end of the module, we briefly discuss how to create new
XML elements/attributes/processing instructions and so on, so that one
grammar of XML can be transformed into a different grammar. Point out that
this is useful in a business-to-business e-commerce situation.
After completing this module, students will be able to:
!
Describe how XSL transforms an XML tree into a different XML result
tree.
!
Write an XSL style sheet with template rules and <xsl:value-of> actions.
!
Use <xsl:apply templates> to apply additional templates.
!
Use the path and filter capabilities of XSL for pattern matching.
!
Achieve complex styling with XSL language constructs.
!
Generate new nodes in the XML result tree.

Materials and Preparation
This section provides you with the required materials and preparation tasks that
you need to teach this module.
Required Materials
To teach this module, you need the following materials:
!
Microsoft PowerPoint
®
file 1905a_04.ppt
!
Module 4, “Displaying an XML Document Using XSL”
!
Lab 4, “Displaying an XML Document Using XSL”

Presentation:
165 Minutes

Lab:
60 Minutes
iv Module 4: Displaying an XML Document Using XSL


Preparation Tasks
To prepare for this module, you should:
!
Read all of the materials for this module.
!
Complete the labs.
Due to the length of the answers to the labs for this course, we were unable
to include them in the Delivery Guide. Please see Appendix A or the
Student CD for the lab answers.
!
Familiarize yourself with the XSL Debugger tool, which is illustrated in the
first Demonstration.

Module 4: Displaying an XML Document Using XSL v


Module Strategy
Use the following strategies to present this module:
!
Transforming XML with XSL
Remind students that we have already seen the effects of XSL style sheets in
Module 2, “Overview of XML Technologies.” Tell students that they will
now see how to create XSL style sheets, rather than only being able to use
them.
To understand how style sheets work, it is imperative that students be aware
of how an XML document maps to a tree of nodes. This mental picture is
fundamental to the students’ understanding of the XSL template-matching
rules.
Also, point out that the syntax shown in this module is the XSL syntax
currently supported in Internet Explorer 5. The W3C has since standardized
XSL Transformations (XSLT), which is different in various respects to XSL
in Internet Explorer 5. Refer students to the W3C site at http://www.w3.org

for more information about XSLT.
!
Using Templates
There are three main aims in this section: to show how to match elements
and attributes in a template rule, to show how to define the output template
(for example, the result of the transformation), and to show how to invoke
secondary templates by using <xsl:apply-templates>.
Point out that you must have a template rule matching the root element in
the XML document. Without this, nothing else in the XSL style sheet is
executed.
Also, many students find the distinction between “/” and “//” confusing.
Deal carefully with this topic.
There is one other surprise for many students: When you specify a match
pattern for <xsl:value-of>, it is not recursive; that is, it retrieves the value of
the specified node but not its descendants.
!
Filtering and Sorting XML
Pattern matching is a subtle topic. The best way to approach it is with plenty
of examples. You might like to show a sample XML document (that is, with
<Employee> and <Name> elements), and describe the meanings of the
various patterns shown in the slides.
In particular, stress that “//” is recursive (giving descendants at any depth),
while “/” is not recursive (giving the direct child only). Also point out that
“*” finds all elements but does not find attributes — you need “@*” if you
wish to match all attributes.
By comparison, most students find filters straightforward. This may be
because filters resemble conventional If statements found in other
programming languages.
!
XSL Language Constructs
This is a short section and can be covered fairly quickly. Students will
immediately recognize these constructs from their experience with other
programming languages. Feel free to make conceptual comparisons with If
statements, For loops, and Case statements found in other languages.
vi Module 4: Displaying an XML Document Using XSL


!
Creating New Nodes Dynamically
Before describing how these XSL constructs work, it is important to
describe why you might use them — for example, to emphasize the use of
XSL to transform one XML grammar into another. This implies the need to
generate XML elements, attributes, and so on; hence the need for these
constructs.
The example in the demonstration shows how to add an HREF attribute to
an <A> element to generate a hyperlink. This technique is used in the lab to
define a hyperlink to an ASP where book details are generated and returned
to the browser.
!
Lab 4: Displaying an XML Document Using XSL
In this lab, students write an XSL style sheet from scratch. The style sheet
transforms the XML book details (returned from Query.asp) into an HTML
table.
Students find the lab quite achievable because most of the tasks have been
covered in a similar way in the module.

Module 4: Displaying an XML Document Using XSL 1


#
##
#

Overview
!
Transforming XML with XSL
!
Using Templates
!
Filtering and Sorting XML
!
XSL Language Constructs
!
Creating New Nodes Dynamically
!
Lab 4: Displaying an XML Document Using XSL
!
Review


One important feature of XML is that it can be transformed into multiple
formats. This module will focus on how to transform XML into HTML format.
Raw data held as XML can be converted into a display format such as HTML
for display in a Web browser. For example, consider two applications that
require the same data but in a different format of XML. In such a case, a
conversion is required when passing that data from one application to the other.
The Extensible Stylesheet Language (XSL) enables this kind of data conversion
in XML.
After completing this module, you will be able to:
!
Describe how XSL transforms an XML tree into a different XML result
tree.
!
Write an XSL style sheet with template rules and <xsl:value-of> actions.
!
Use <xsl:apply templates> to apply additional templates.
!
Use the path and filter capabilities of XSL for pattern matching.
!
Achieve complex styling with XSL language constructs.
!
Generate new nodes in the XML result tree.

Slide Objective
To provide an overview of
the module topics and
objectives.
Lead-in
In this module, you will learn
about displaying XML data
in a Web browser by using
the Extensible Stylesheet
Language, or XSL.
2 Module 4: Displaying an XML Document Using XSL


#
##
#

Transforming XML with XSL
!
Transforming XML Trees
!
Mapping XML Trees
!
Mechanics of XSL Transformations
!
Demonstration: Using the XSL Debugger


XML is a very good mechanism for describing data. However, this raw format
may not always be the best way to export or display that data. For example,
although Internet Explorer 5.0 understands XML notations and syntax rules,
when a raw XML document containing book information is loaded into Internet
Explorer 5.0, it is displayed as a collapsible hierarchy of elements and child
elements. This information would be far better displayed as a table, with
carefully chosen fonts and color schemes to make the user interface visually
attractive.
You can think of an XML document as a tree structure. Therefore, when
converting XML from one format to another, the source tree containing the data
must be converted into a result tree that represents a different format. XSL style
sheets provide a way of achieving this conversion. An XSL style sheet defines
the rules that should be applied to the parts of the XML source tree in order to
convert them to the equivalent parts of the XML result tree.
Slide Objective
To introduce the general
concept of transforming an
XML tree into a different
format.
Lead-in
For a Web browser to
display XML in a user-
friendly way, the XML must
be converted into HTML.
XSL style sheets provide a
way to achieve this type of
transformation.
Module 4: Displaying an XML Document Using XSL 3


Transforming XML Trees
!
Using XSL and XSL processor for transforming XML
!
Attaching an XSL style sheet to an XML document
XML document
(different format)
XSL processor
XSL processor
HTML document
(XML-conformant)
XML
document
XSL style
sheet
+
<?xml-stylesheet type="text/xsl"
href="Employees.xsl" ?>
<?xml-stylesheet type="text/xsl"
href="Employees.xsl" ?>


The Extensible Stylesheet Language was first defined in August 1997 as a style
language for XML.
The aim of XSL is to provide a simple but powerful style-sheet syntax. One of
the main uses of XSL is to define how XML documents should appear in a
presentation medium such as a browser. XSL also enables the transformation of
an XML document from one format to another.
To transform a given XML document into a different format, XSL requires an
XSL processor that will apply an XSL style sheet to the XML document. An
XSL processor is built into the Microsoft
®
XML COM component.
Using XSL style sheets
An XSL style sheet contains rules that determine how an XSL processor
converts the XML source tree into the XML result tree. Each rule consists of a
pattern that identifies the elements or attributes to be transformed, and a
template that is used to define the result of the transformation. To attach an
XSL style sheet to an XML document, add a processing instruction such as the
following to the XML document:
<?xml-stylesheet type="text/xsl" href="Employees.xsl" ?>

This will cause an XML-aware application such as Internet Explorer 5.0 to
invoke the XSL processor and pass to the processor the XML source document
together with the style sheet.
The XSL processor translates the XML document into a different form of
XML. The output generated from an XSL style sheet can be any document,
such as an XML or EDI document. When transforming an XML document into
HTML, bear in mind that the HTML must be XML-compliant. For example,
each start tag must have a corresponding end tag, and case sensitivity rules.
Slide Objective
To describe the process of
transforming an XML
document from one format
to another.
Lead-in
Transforming an XML
document into another
format requires an XSL
processor. The XSL
processor applies the given
style sheet to the XML
document and creates a
new XML tree as a result.
4 Module 4: Displaying an XML Document Using XSL


If more than one style sheet is attached to a document, only the first one is used.
All subsequent style sheets are ignored.
Using XSL to transform XML into different XML
XSL also has the potential to help build sophisticated e-commerce solutions. To
understand the role of XSL in e-commerce, consider the following example.
Companies A and B constantly exchange data. Both of these companies
produce widgets, and need to describe their customer orders. Each widget has a
part number, and therefore each order consists of a series of part numbers and
associated quantities. So far, the two companies’ business models are identical.
However, when writing its XML-aware applications, Company A has decided
to represent both the part number and the quantity as separate elements, leading
to the following type of nested hierarchy:
<Order>
<OrderItem>
<ItemID>12980-235</ItemID>
<Quantity>200</Quantity>
</OrderItem>
</Order>

In contrast, Company B has decided to represent all of this order-item
information in a single element and to use attributes for the part number and
quantity as follows:
<Order>
<OrderLine PartNo=”12980-235” NumRequired=”200”/>
</Order>

Not only are the formats of these two XML documents different, but the names
of the attributes used by Company B also differ from the names of the elements
used by Company A. In such a scenario, you can use XSL to transform the
XML document of Company A into the format used by Company B, or vice
versa.

A word of caution with regard to XSL Transformation (XSLT) and XSL:
The draft standards are in a constant state of flux, and syntax that is valid today
might be invalid in a few months’ time. The discussions in this course are based
on the fifth draft standard of the XSLT specification, dated 9 July 1999, which
is available at the Web site http://www.w3.org/TR/WD-xslt
. The latest draft
specification for XSL is draft three, dated 21 April 1999, which is available at
the Web site http://www.w3.org/TR/WD-xsl
.
For the purposes of this course, we will concentrate on XSLT as implemented
in the Microsoft XML COM component. At the time of this writing, few
applications implement the formatting objects as specified by the W3C.
Subsequent references to XSL will implicitly refer to features provided by
XSLT.

Note
Module 4: Displaying an XML Document Using XSL 5


Mapping XML Trees
XML document
<employees>
<employee ID="123">
<name>Jake</name>
<salary>23000</salary>
</employee>
...
</employees>
Document root
<employees>
<employee>
ID <name> <salary>
"Jake" "23000"

"123"
Tree structure


The transformation process of an XML document involves two steps:
!
First, the XML source tree is transformed into a result tree.
The structure of the result tree might be entirely different from the structure
of the source tree, depending on the transformation rules specified in the
style sheet. For example, the style sheet might reorder and filter the
elements and build a table of contents on the fly. Another possibility might
be to take the results of a database query, expressed in XML, and sort the
query result in tabular format. This process of transforming the source tree
into a result tree is known as XSL Transformation (XSLT).
!
Once the tree transformation has taken place, a series of formatting rules can
be defined in the style sheet, indicating how the result tree should be
presented visually.

Processing an XML document with an XSL style sheet
When a user requests an XML document that has an XSL style sheet, the XSL
processor processes the XML document before it is displayed on the client. The
XML is parsed to build a DOM tree, and then the XSL is parsed. Each element
in the XSL is then matched to a node in the XML DOM tree. When the
processor finds an element that matches a template rule’s pattern, it outputs the
output template associated with that rule.
Slide Objective
To describe how an XML
document is represented as
a tree of nodes in memory.
Lead-in
When an XML document is
loaded into a parser, the
parser builds a tree in
memory to represent the
various nodes in the
document.
6 Module 4: Displaying an XML Document Using XSL


Mechanics of XSL Transformations
!
An XSL document is a well-formed XML document
$
XSL document has a single <xsl:stylesheet> element
$
Template rules are defined as <xsl:template> elements
$
Output templates are the contents of the <xsl:template>
elements and define the transformation required
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/TR/WD-xsl">
template rule 1
output template
template rule 2
output template
</xsl:stylesheet>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/TR/WD-xsl">
template rule 1
output template
template rule 2
output template
</xsl:stylesheet>


An XSL processor takes an XML document as input and applies transformation
rules to it, as expressed in an XSL style sheet. The result is a new XML
document.
Format of an XSL document
The following is a skeleton XSL document:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
template rule 1
output template
template rule 2
output template
</xsl:stylesheet>

XSL style sheets are themselves well-formed XML documents. The root
element must be <xsl:stylesheet>, the namespace must be exactly as shown, and
the case must also match exactly. The style sheet contains a list of template
rules:
!
Each template rule has a pattern specifying the elements of the source XML
document.
!
Each template rule has an output template that is output when the pattern is
matched. The output template usually includes some (or all) of the data in
the source XML document.

Slide Objective
To introduce the format of
an XSL style sheet.
Lead-in
XSL is itself a form of XML.
The XSL namespace
defines a set of instructions
for the XSL processor.
Using these, you can
specify a pattern to match
and a template to output
when the pattern is found in
the XML document.
Delivery Tip
Remind students about
namespaces and how they
are represented.
Also tell them that
namespaces are case-
sensitive.
Delivery Tip
The xmlns:xsl namespace is
a Microsoft requirement; it is
not part of the standard.
Module 4: Displaying an XML Document Using XSL 7


Demonstration: Using the XSL Debugger


In this demonstration, you will see how to use the XSL Debugger tool to view
the output of an XSL style sheet. This tool can help diagnose problems in an
XSL style sheet. You will also see how to install an XSL viewer that integrates
with Internet Explorer 5.0 and provides immediate feedback on the output of an
attached XSL style sheet.
XSL Debugger
The XSL Debugger, xsl-debugger.htm, is included in the folder
\Democode\Mod04 folder on the Student CD-ROM. The tool comprises a set of
HTML documents, and appears as follows in Internet Explorer 5.0.

Slide Objective
To show how to use the
XSL Debugger to view the
output of an XSL
transformation.
Lead-in
In this demonstration, you
will see how to use the XSL
Debugger, a tool from
Microsoft for viewing the
result of an XSL
transformation.
Delivery Tip
1. In Notepad, open the file
employees.xml from the
folder
\InetPub\WWWRoot\1905\D
emoCode\Mod04. Note that
there is a style sheet
attached to the document.
2. Now open employees.xsl
and briefly describe the
contents of the style sheet.
3. Open employees.xml
from Internet Explorer 5.0.
The XML data is displayed
as an HTML table, as a
result of the style sheet.
4. In Internet Explorer 5.0,
open xsl-debugger.htm.
Make sure that
employees.xsl is displayed
in the left pane and
employees.xml is displayed
in the right pane.
5. Make sure that the Show
Source check box is
selected.
6. Click Run. A pop-up
menu is displayed. Click
Step to step through the
style sheet. The results of
the XSL transformation are
displayed at the bottom of
the page.
8 Module 4: Displaying an XML Document Using XSL


XSL Output Viewer
The XSL viewer utility is available on the Student CD-ROM in the
\Sampapps\xml diagnostics\XSL Output Viewer folder.
!
To install the XSL Viewer utility
• On the Student CD-ROM, right-click the file msxmlvw.inf in the folder
\Sampapps\xml diagnostics\XSL Output Viewer, and then click Install.

Delivery Tip
1. Open Windows Explorer
and navigate to
\InetPub\WWWRoot\1905\D
emoCode\Mod04.
2. Right-click msxmlvw.inf,
and then click Install to
install the XSL viewer utility.
3. Launch Internet Explorer
5.0 (restart it if it is already
running), and open
Employees.xml from the
same folder.
4. Right-click in the main
window of Internet Explorer
5.0, and then click View
XSL Output.
Module 4: Displaying an XML Document Using XSL 9


#
##
#

Using Templates
!
Matching the Root Element
!
Matching XML Nodes
!
Format of an Output Template
!
Outputting Nodes
!
Demonstration: Outputting Values of Child Elements
!
Invoking Additional Template Rules
!
Practice: Recursively Applying Templates


There are two key stages of using XSL as a transformation mechanism for
XML documents. The first is to match the appropriate elements in the input
tree. The second is to generate the correct output tree. In this module, you will
learn how to match XML elements and how to generate an output tree.
Slide Objective
To introduce the module
topics.
Lead-in
Now let’s look at how to
create an XSL template to
format an XML document.
10 Module 4: Displaying an XML Document Using XSL


Matching the Root Element
!
Use <xsl:template match> to match different parts of
the XML document
!
Any nodes not matched will not be output
!
Begin by matching the root element of the
XML document
<xsl:stylesheet xmlns:xsl=
"http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
output template for root element
</xsl:template>
</xsl:stylesheet>
<xsl:stylesheet xmlns:xsl=
"http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
output template for root element
</xsl:template>
</xsl:stylesheet>


XSL style sheets contain one or more template rules. Each template rule is an
<xsl:template> element.
The match attribute of the <xsl:template> element contains the pattern to be
matched in the source XML document tree. Only elements or attributes
(generically referred to as nodes) that match a template rule in the XSL style
sheet will be transformed. Any node in the source XML document that is not
matched by a template rule in the style sheet will be ignored.
Matching the root element
Certain hierarchy rules must be followed when using Microsoft’s XSL
processor. You must always begin an XSL style sheet by matching the root
element, or “/”. If you fail to do this, the processor will examine no other
templates and none of your transformations will take place.
When a template rule is matched, its output template will be invoked for every
matching node. This implies that there is a current node that is being
transformed by the output template.
Slide Objective
To examine the matching of
elements in the source XML
document.
Lead-in
One key question that arises
when transforming an XML
document into another
format is what elements and
attributes should be
transformed.
Delivery Tip
Stress the point that you
must begin an XSL style
sheet by matching the root
element, and that only
nodes that match a template
rule in the XSL style sheet
will be transformed. Any
node in the source XML
document that is not
matched by a template rule
in the style sheet will be
ignored.
Module 4: Displaying an XML Document Using XSL 11


Matching XML Nodes
!
Match relative to the current node
!
Matching elements
!
Matching multiple elements
<xsl:template match="*">
<xsl:template match="Employee">
<xsl:template match="//Employee">
<xsl:template match="Employee//Name">
<xsl:template match="Employee/Name">
<xsl:template match="*">
<xsl:template match="Employee">
<xsl:template match="//Employee">
<xsl:template match="Employee//Name">
<xsl:template match="Employee/Name">


XSL style sheets use pattern-matching rules to match nodes in the XML
document tree to template rules in the style sheet.

The pattern matching syntax described here is also used in XPath. XPath
is a W3C-recommended technology that describes how to locate specific nodes
in an XML document by using pattern matching to indicate the position of the
node in the document. For more information about XPath, go to the Web site
http://www.w3.org/TR/1999/REC-xpath-19991116.html.

Matching all elements
If you wish to process every element in the source XML document, include a
template with the pattern “*”. By using this wildcard character, any unmatched
source element will use this template.
For example, the following template matches all source elements that are not
matched by a more specific template:
<xsl:template match="*">
output template
</xsl:template>

Slide Objective
To discuss the use of XSL
pattern matching to match
other nodes in the XML
document.
Lead-in
There are different ways to
match nodes in the source
XML document to template
rules in the XSL style sheet.
Note
12 Module 4: Displaying an XML Document Using XSL


Matching a specific element
If you wish to process a specific element, include a template that contains the
name of the element in the pattern. For example, the following template
matches <Employee> elements that are children of the current node:
<xsl:template match="Employee">
output template
</xsl:template>

Matching a specific element by path
It is also possible to match elements according to their absolute or relative
positions in the source XML document.
To find elements at any depth below the root node, use the recursive descent
path operator (//). The following example matches all <Employee> elements at
any level in the document:
<xsl:template match="//Employee">
output template
</xsl:template>

To find elements at any depth below a specific node, use the recursive descent
path operator after a specific node name. The following example matches all
<Name> elements that are descendents at any level of the <Employee>
element:
<xsl:template match="Employee//Name">
output template
</xsl:template>

To find elements that are direct children of a specific node, use the child path
operator (/). The following example matches all <Name> elements that are
direct children of the <Employee> element:
<xsl:template match="Employee/Name">
output template
</xsl:template>

Matching multiple elements
When you design a style sheet, it is likely that some elements in the source
XML document will match more than one template pattern. In this situation, the
XSL processor selects the last template that matches, and only executes that
template rule. The other matching template rules for the element are not
executed. For example “*” would match anything that is not specifically called
out, such as the author elements. The “Employee” element would match
employees, which are not otherwise matched, and “Employee/Name” overrides
the more general match for the employees.
Module 4: Displaying an XML Document Using XSL 13


Format of an Output Template
!
Output templates define how elements and attributes
in the XML document will be transformed
!
For example:
$
Translate an XML document into HTML format
<xsl:template match=“Employee/Name">
<P>
<HR/>
output employee’s name
<HR/>
</P>
</xsl:template>
<xsl:template match=“Employee/Name">
<P>
<HR/>
output employee’s name
<HR/>
</P>
</xsl:template>



When using XSL style sheets to convert XML into HTML, certain
restrictions apply. The XSL output templates must produce well-formed HTML
in order to be successfully transformed.

After you have identified which element you wish to transform, you must
dictate the type of transformation to be carried out on the element. This is called
the output template. The output template is the content of the <xsl:template>
element. The output template can contain a mixture of:
!
Fixed text (anything from a single character to multiple lines)
!
Tags that will form part of the XML tree in the output document
!
Element and attribute values from the source XML document
!
Other XSL constructs, such as looping and decision-making constructs to be
discussed later

The following fragment shows a part of a style sheet used to convert XML to
HTML:
<xsl:template match="Employee/Name">
<P>
<HR/>
output employees name
<HR/>
</P>
</xsl:template>

Whenever the XSL processor encounters a <Name> element in the source XML
document that is a child element of an <Employee> element, it will transform
the <Name> element into an HTML paragraph containing two horizontal lines,
one on either side of the employee’s name.
Slide Objective
To examine the form and
style of output templates.
Lead-in
Once you have identified
which element you wish to
transform, you must dictate
the type of transformation to
be done on the element.
Note
14 Module 4: Displaying an XML Document Using XSL


Outputting Nodes
!
<xsl:value-of> outputs the text content of an element
and all its descendents
!
<xsl:value-of select = ... > outputs the text content of
selected descendents
<xsl:template match="/">
<xsl:value-of />
</xsl:template>
<xsl:template match="/">
<xsl:value-of />
</xsl:template>
<xsl:template match="/">
<xsl:value-of select = "Name" />
<xsl:value-of select = "//Employee" />
</xsl:template>
<xsl:template match="/">
<xsl:value-of select = "Name" />
<xsl:value-of select = "//Employee" />
</xsl:template>


When creating an output template, you will frequently want to include the value
of the matched source XML node. The XSL element <xsl:value-of> outputs the
value of a source node.
The <xsl:value-of> element can appear one or more times in the output
template.
Outputting the text of the matched node
When the <xsl:value-of> element is used in its simple form,<xsl:value-of/>, it
will evaluate to the value of the currently selected node. If the currently selected
node is an element containing child elements, then the value of these child
elements will be recursively output.
For example, the following will output all child elements of the root node:
<xsl:template match="/">
<xsl:value-of />
</xsl:template>

Slide Objective
To examine how to output
the contents of an element
or the value of an attribute.
Lead-in
You will frequently want to
include a part of the source
XML document in the output
XML document. The
<xsl:value-of> XSL element
provides this functionality.
Module 4: Displaying an XML Document Using XSL 15


Outputting a descendent of the matched node
The alternative form of the <xsl:value-of> element allows you to supply a
selection criterion. In this case, only the value of the selected node is output.
The selection criterion can be any normal XSL pattern.
For example, the following matches all the direct descendents named “Name”:
<xsl:value-of select = "Name" />

And this matches all the descendents (at any level) named “Employee”:
<xsl:value-of select = "//Employee" />

Be careful when using this form of the <xsl:value-of> element. Only the first
node matching the selection criterion will be output.
Delivery Tip
Be prepared to answer
questions that students may
have about using this form
of the <xsl:value-of>
element.
16 Module 4: Displaying an XML Document Using XSL


Demonstration: Outputting Values of Child Elements


In this demonstration, you will learn how to apply a simple XSL style sheet to
an XML document.
The style sheet used in this demonstration outputs the text content of each XML
element.
Slide Objective
To demonstrate how to write
a simple XSL style sheet to
obtain the text content of
elements in an XML
document.
Lead-in
In this demonstration, you
will learn how to apply a
simple XSL style sheet to an
XML document. The style
sheet outputs the text
content of each XML
element.
Delivery Tip
1. In Notepad, open the file
GetAllText.xsl from the
folder
\InetPub\WWWRoot\1905\D
emoCode\Mod04.
2. In Notepad, open the file
employees.xml from the
folder
\InetPub\WWWRoot\1905\D
emoCode\Mod04 and attach
the GetAllText.xsl style
sheet.
3. In Internet Explorer 5,
open employees.xml. Note
that only elements are
output.
4. Edit GetAllText.xsl to use
the output rule <xsl:value-of
select=”//employee” />.
Refresh employees.xml in
the browser. Only the data
for the first employee is
displayed.
5. Edit GetAllText.xsl to use
the output rule <xsl:value-of
select=”//name” />. Refresh
employees.xml in the
browser. Only the name of
the first employee is
displayed.
Module 4: Displaying an XML Document Using XSL 17


Invoking Additional Template Rules
!
<xsl:apply-templates> invokes template rules for
all descendents
!
<xsl:apply-templates select="pattern"> invokes
template rules for selected descendents
<xsl:template match="/">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="/">
<xsl:apply-templates />
</xsl:template>
<xsl:template match= "Employees">
<xsl:apply-templates select = "/Name" />
<xsl:apply-templates select = "//Salary" />
</xsl:template>
<xsl:template match= "Employees">
<xsl:apply-templates select = "/Name" />
<xsl:apply-templates select = "//Salary" />
</xsl:template>


An XSL style sheet must contain a template rule to match the root element, “/”.
The XSL processor will always look for this rule first and then apply the output
template to the root node. To invoke other template rules in the style sheet,
include the XSL <xsl:apply-templates> element in the root node rule. This will
lead to a cascade effect through all of the template rules in the style sheet.
<xsl:template match="/">
<xsl:apply-templates />
</xsl:template>

Applying templates
There are two forms of the <xsl:apply-templates> element:
!
A simple <xsl:apply-templates> element will iterate through the direct
descendents of the current node and apply any template rules that match
them.
!
The <xsl:apply-templates select = “pattern”> element applies template rules
only to selected descendents.


As the XSL specification has evolved, certain parts have been subject to
different interpretations. The effect of the <xsl:apply-templates> element is one
such part. The issue here is whether templates should be applied by default
when processing a node, or only if specifically instructed to by use of an
<xsl:apply-templates> element. This means that for some processors, for
example the Lotus LotusXSL, a single <xsl:apply-templates> element in the
root node output template will result in templates being applied recursively to
all nodes in the source tree, rather than just those that are direct descendents of
the root node. This portability issue should be resolved over time as the related
specifications are finalized.

Slide Objective
To discuss the need to
apply templates in order to
propagate rule matching.
Lead-in
To apply other template
rules, you must explicitly tell
the XSL processor which
nodes you wish to apply the
templates to.
Delivery Tip
You must always have a
template for the root
element or no other
matching will take place.
Once the root element is
matched, “select” will match
whatever you request to be
matched.
Note
18 Module 4: Displaying an XML Document Using XSL


Example of applying templates
The following XSL style sheet shows how to apply different templates to
different XML elements.
!
Each <Employee> element is displayed on a different line in the browser.
!
Each <Name> element is displayed in a 36pt font size.
!
Each <Salary> element is displayed in italics.

<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<xsl:apply-templates select="//Employee" />
</xsl:template>

<xsl:template match="Employee">
<P>
<xsl:apply-templates select="Name" />
<xsl:apply-templates select="Salary" />
</P>
</xsl:template>

<xsl:template match="Name">
<SPAN style="font-size:36pt">
<xsl:value-of />
</SPAN>
</xsl:template>

<xsl:template match="Salary">
<I><xsl:value-of /></I>
</xsl:template>

</xsl:stylesheet>

The style sheet defines four different templates. The first template matches the
root element of the XML document and applies any template rules that match
the "//Employee" pattern.
<xsl:apply-templates select="//Employee" />

The XSL processor scans the XML document for <Employee> elements at any
depth beneath the current element. The // operator is the recursive path operator,
and ensures that the XSL processor finds <Employee> elements at any depth
and not just direct children of the current element.
Once an <Employee> element is found in the XML document, the XSL
processor applies the template rule for <Employee>. This is the second template
rule in the style sheet. The output template for this template rule is as follows:
<P>
<xsl:apply-templates select="Name" />
<xsl:apply-templates select="Salary" />
</P>

This output template inserts a <P> element and then recursively applies any
rules that match <Name> and <Salary> elements.
Module 4: Displaying an XML Document Using XSL 19


The template rule for <Name> outputs the name value in a 36pt font size. The
template rule for <Salary> elements outputs the salary value in italics.

One problem with the application of templates is that style sheets,
being pattern-based, are somewhat error-prone. Care must be taken not to
inadvertently miss the nodes you wish to match. The same is true of the nodes
you do not wish to match. An XSL debugger is available from the Web site
http://msdn.microsoft.com/xml
. The debugger allows you to see how the XSL
style sheet transforms a source XML document, and includes single-stepping
facilities that help to isolate potential errors in the style-sheet templates.

Caution

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay

×

×