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 res
Trang 1Lab 4: Displaying an XML Document Using
XSL 44
Review 52
Module 4: Displaying an XML Document Using XSL
Trang 2to 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
Trang 3Instructor 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
Trang 4Preparation 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
Trang 5Module 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
Trang 6! 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
Trang 7! 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
In this module, you will learn
about displaying XML data
in a Web browser by using
the Extensible Stylesheet
Language, or XSL
Trang 8# 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
XSL style sheets provide a
way to achieve this type of
transformation
Trang 9Transforming XML Trees
! Using XSL and XSL processor for transforming XML
! Attaching an XSL style sheet to an XML document
XSL style sheet
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
processor applies the given
style sheet to the XML
document and creates a
new XML tree as a result
Trang 10If 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>
<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
Trang 11The 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
loaded into a parser, the
parser builds a tree in
memory to represent the
various nodes in the
document
Trang 12Mechanics of XSL Transformations
! An XSL document is a well-formed XML document
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
! 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
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
Trang 13Demonstration: 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
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
Trang 14XSL 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
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
Trang 15! 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
Trang 16Matching 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
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
Trang 17The 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
Trang 18Matching 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/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
Trang 19Format of an Output Template
! Output templates define how elements and attributes
in the XML document will be transformed
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:
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
Trang 20<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
Trang 21Outputting 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
Trang 22Demonstration: 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
Trang 23Invoking 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= "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
Trang 24Example 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" />
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:
Trang 25The 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
Trang 26Practice: Recursively Applying Templates
In this practice, you will create an XSL style sheet that transforms an XML document into HTML suitable for display in Internet Explorer 5.0
! Create an XSL style sheet
1 Create a new file named Transform.xsl in the folder
\InetPub\WWWRoot\1905\Practices Add an <xsl:stylesheet> root element for the style sheet:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
</xsl:stylesheet>
2 Create a template rule for the root element of the XML document Define the output template so that it creates HTML tags and applies the templates for all <book> elements:
In this practice, you will
create an XSL style sheet
that transforms an XML
document into HTML
Trang 274 Create a template rule for <title> elements Define the output template so that it displays the book title in bold:
! Link the style sheet to the XML document
1 Edit Books.xml in the folder \InetPub\WWWRoot\1905\Practices, and add a processing instruction to link Transform.xsl to the XML document:
<?xml-stylesheet href="Transform.xsl" type="text/xsl"?>
2 Open the file Books.xml in the browser to view the results The XML document should be displayed as follows
Trang 28# Filtering and Sorting XML
! Pattern Matching by Position
! Filters
! Additional Filters
! Sorting
! Practice: Applying Patterns, Filters, and Sorting
In any real XML-based system, there is the likelihood that at least some of the XML documents used or exchanged will be somewhat complex The simple examples of pattern matching we have seen so far are not powerful enough to drive the types of transformations required in these real-world cases This section will examine more powerful pattern-matching and selection features available in XSL
Slide Objective
To introduce more powerful
mechanisms for selecting
elements
Lead-in
Thus far, we have used
fairly simple criteria for
matching elements Now we
move on to more powerful
matching syntax
Trang 29Pattern Matching by Position
! Select specific elements or attributes by position and hierarchy
Path operator Description
/ "child" path operator
"recursive descent" path operator
“current context" path operator
"attribute" path operator
"wildcard" path operator
"parent" path operator
or attributes that match the pattern:
! Child The simplest form of path operator is the forward slash (/), or child operator This is used to indicate a new level of element hierarchy in the same way as the backslash “\”, which indicates a new level of directory hierarchy in the Windows® file system The child path operator selects elements that are immediate children of the specified element
For example, the following output template selects <Name> elements that are direct children of <Employee> elements:
<xsl:apply-templates select="Employee/Name" />
You can use the child operator in either a relative or absolute way
• A relative path starts from the current node and works downward Employee/Name uses a relative path
• An absolute path specifies the full path from the root element to the node being matched Absolute paths start with the forward slash (/) operator to represent the root of the XML document For example, the pattern /Employees/Employee selects <Employee> elements, which are direct children of the root element <Employees>
Slide Objective
To examine the different
path operators that can be
used to select XML nodes
Lead-in
Path operators allow you to
specify the required element
or attribute in the input
document by relative or
absolute location
Trang 30! Recursive descent The double slash (//), or recursive descent path operator, selects descendent elements at any level of the specified element
For example, the following output template selects <Name> elements that are descendents (at any depth) of <Employee> elements:
<xsl:apply-templates select="Employee//Name" />
! Current context The period (.), or current context path operator, selects elements relative to the current element
For example, the following output template selects all <Name> elements that are descendent at any depth from the current node:
<xsl:apply-templates select=".//Name" />
! Parent The double period ( ), or parent path operator, selects the parent element
For example, /Name matches the <Name> elements that are children of the
current element’s parent, for example, the current node’s siblings
! Attribute The commercial “at” sign (@), or attribute path operator, selects attributes
of the specified element
For example, the following output template selects <ID> attributes of
<Employee> elements:
<xsl:apply-templates select="Employee/@ID" />
! Wildcard The asterisk (*), or wildcard path operator, matches any element or attribute
For example, the following output template selects all child elements of
<Employee> elements:
<xsl:apply-templates select="Employee/*" />
This output template also selects all attributes of <Employee> elements
<xsl:apply-templates select="Employee/@*" />