Download presentation
Presentation is loading. Please wait.
Published byLaurence Hart Modified over 8 years ago
1
Copyright @ 1999 costello1 XSL by Example (part 2) Roger L. Costello copyright @1999
2
Copyright @ 1999 costello2 Hello World xsl:variable This XSL element allows you to create a variable to hold a value (which could be a string or a node list). The variable is referenced by $variable-name This creates a variable called hello, that has a value which is the literal string, ‘Hello World’. We could use this variable as follows: Value = This will output: Value = Hello World hello
3
Copyright @ 1999 costello3 xsl:variable … This creates a variable called book, that has a value which is a subtree. We could use this variable as follows: Title = Author = This will output: Title = Illusions The Adventures of a Reluctant Messiah Author = Richard Bach book Book Author Title Date... Richard Bach Illusions The Adventures of a Relucatant Messiah 1977
4
Copyright @ 1999 costello4 xsl:variable A variable is “write once, read many”. That is, you can assign a variable a value only once, but then you can retrieve the value of the variable many times. A variable has a scope limited to the XSL element that it is defined in. Its scope starts where it is defined and extends to the end of the XSL element that it is defined in.
5
Copyright @ 1999 costello5 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">......... top-level-variable root-variable for-each- variable book- variable VariableScopeTest.xsl Scope of the variables
6
Copyright @ 1999 costello6 Problem Suppose that we want to create a variable, Authors, and we want this variable to contain a list of the authors in the BookCatalogue, with each author separated by a slash. How would you create such a variable? Here’s what you might attempt to do: 1]/Author"> Output: Paul McCartney
7
Copyright @ 1999 costello7 Let’s add some statements to trace this example 1]/Author"> Output: Paul McCartney Paul McCartney/ Paul McCartney/Richard Bach Paul McCartney/ <--- Why did we loose the previous Author? That Author went out of scope. Paul McCartney/J. Krishnamurti Paul McCartney Obviously, this approach doesn’t work. So how do we do it?
8
Copyright @ 1999 costello8 Here’s what we would like to do Authors Open up the Authors box Add this iteration’s author and a slash to the open Authors box Iterate through each author, adding into the open box Paul McCartney/Richard Bach/J. Krishnamurti Close the box Authors Paul McCartney … / … Richard Bach … / … J. Krishnamurti
9
Copyright @ 1999 costello9 Problem - Solution In all previous examples of creating a variable we declared the name of the variable and then had a select attribute which gave the variable its value. We can omit the select attribute: - Do stuff in here. All output will go into the Authors box.
10
Copyright @ 1999 costello10 Problem - Solution 1]/Author"> Output: Paul McCartney/Richard Bach/J. Krishnamurti Creating the variable
11
Copyright @ 1999 costello11 Example Banana NOKAI 918+ First and Last Freedom Illusions The Adventures of a Reluctant Messiah Orange Oak Siddhartha Peach DynamicTable.xml FruitsBooks Banana Orange Peach First and Last Freedom Illusion The Adventures of a Reluctant Messiah Siddhartha DynamicTable.html Problem: write an XSL stylesheet to generate the above HTML table from the XML document at the left. XSL?
12
Copyright @ 1999 costello12 The Key to this Problem (Pseudocode) For each Rows/Row do start an HTML row (output ) set a variable, cols, equal to the list of columns for that row For each../../Columns/Column start an HTML table data element (output ) set a variable, colname, equal to the name of the column (in the name attribute) output the column referenced by cols that has the same name as that in colname end the HTML table data element (output ) end the HTML row (output ) cols Column (name=“Fruits”) Banana Column (name=“Cellphones”) NOKAI 918+ Column (name=“Books”) The First and Last Freedom colname Fruits (cols points to a Nodelist)
13
Copyright @ 1999 costello13 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> Dynamic Table DynamicTable.xsl Thanks to James Clark for this solution!
14
Copyright @ 1999 costello14 xsl:param This allows you to pass parameters to a template –immediately after declare an xsl:param variable... This declares an xsl:param variable whose name is “indent”.
15
Copyright @ 1999 costello15 xsl:param You can, of course, have more than one param variable. Simply declare all the param variables immediately after When you invoke the template rule you can pass values to the param variables as follows: This apply-templates rule will invoke the template rule defined on the previous page. The param variable called “indent” in that template rule will be assigned the value defined above (' ').
16
Copyright @ 1999 costello16 Problem Problem. As you may know, the W3 is creating a new schema language to replace DTDs. There have been numerous submittals by companies as candidate replacement languages. One of those is called XDR (XML Data Reduced). For this problem you are to print the hierarchy defined by an XDR document. You are to use indentation to show the child-parent relationship.
17
Copyright @ 1999 costello17 Cellphone.xdr (snippet) cellphone.e-catalog model technology price dimensions weight battery display.features memory.features call.features output “cellphone.e-catalog contains model. model contains technology, price, dimensions, etc.”
18
Copyright @ 1999 costello18 SchemaStyler.xsl (snippet)
19
Copyright @ 1999 costello19 xsl:choose xsl:choose allows you to elegantly express multiple conditional tests. Here’s the structure: [action] [action] [action]
20
Copyright @ 1999 costello20 substring-after() String Function Here’s the form of this string function: substring-after(string, pattern) Example: “Get the contents of the current node and put it into the variable called ‘value’. Then extract from the content of ‘value’ the string that follows ‘ICAO:’”. ICAO: Bos substring-after($value, ‘ICAO:’) Bos value
21
Copyright @ 1999 costello21 starts-with() String Function Here’s the form of this string function: starts-with(string, pattern) Example: [action] “If the contents of the current node starts with the string, ‘ICAO:’ then do [action]”.
22
Copyright @ 1999 costello22 xsl:element Suppose that you are writing a stylesheet to generate an XML document (rather than an HTML document). Obviously, you will need your stylesheet to output elements. –xsl:element is used to create elements [contents of the new element] [contents of the new element] creates
23
Copyright @ 1999 costello23 Example There are several different ways to identify airports: –ICAO code: e.g., BOS is the ICAO code for the Boston airport –Lat/Lon: e.g., 74.3N, 123.0W is the lat/lon of the Boston airport I have an XML document which contains elements. The contents of a element is a string with one of the following forms: ICAO: code or LatLon: value For this example you are to write an XSL document which transforms this XML document into another XML document in which is transformed into or depending upon the content ICAO: Bos LatLon: 74.31W, 106.5N ICAO: SLT ICAO: MOL LatLon: 43.01W, 116.8N Bos 74.31W, 106.5N SLT MOL 43.01W, 116.8N locations.xml
24
Copyright @ 1999 costello24 locations.xsl (snippet) if the content of this element starts with ICAO: then output the content (minus the ICAO: prefix)
25
Copyright @ 1999 costello25 (Much) More on xsl:number This is used to apply numbers to your output document 3 bedrooms 1 1/2 baths attic paneled basement new carpet Asking Price: $120K House For Sale 1. 3 bedrooms 2. 1 1/2 baths 3. attic 4. paneled basement 5. new carpet 6. Asking Price: $120K Use xsl:number to number the house features House.xml
26
Copyright @ 1999 costello26 xsl:number (Simplest Form) There are several attributes that can be used with xsl:number. However, here is its simplest form:. By default xsl:number will generate a number based upon the position of the element in the document, e.g, for the first feature xsl:number will generate the number 1, for the second feature xsl:number will generate the number 2, and so forth.
27
Copyright @ 1999 costello27 value Attribute of xsl:number The xsl:number element may contain an attribute, value. The value of this attribute is a number. This number is the number that xsl:number will output.
28
Copyright @ 1999 costello28 vs –The number generated is based upon the position of the element in the document –The number generated is based upon the position of the element in the currently selected node set The next two slides demonstrate the differences
29
Copyright @ 1999 costello29 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> House for Sale House For Sale. House For Sale 1. 3 bedrooms 2. 1 1/2 baths 3. attic 4. paneled basement 6. Asking Price: $120K Notice that the numbering is not sequential (the number 5 is missing). This is because numbers the source tree (i.e., the original XML document) Select all features except the one that says ‘new carpet’.
30
Copyright @ 1999 costello30 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> House for Sale House For Sale. House For Sale 1. 3 bedrooms 2. 1 1/2 baths 3. attic 4. paneled basement 5. Asking Price: $120K Notice that the numbering is sequential. This is because numbers the node set (i.e., the set of nodes that are selected).
31
Copyright @ 1999 costello31 format attribute of xsl:number In the previous example we saw how to generate numbers, and we saw that the generated numbers were 1, 2, 3, etc. With the format attribute we can specify the format of the generated number, i.e., 1, 2, 3 or I, II, III, or A, B, C, or A.1, A.2, A.3, or...
32
Copyright @ 1999 costello32 format attribute of xsl:number. House For Sale A. 3 bedrooms B. 1 1/2 baths C. attic D. paneled basement E. new carpet F. Asking Price: $120K
33
Copyright @ 1999 costello33 format attribute of xsl:number. House For Sale I. 3 bedrooms II. 1 1/2 baths III. attic IV. paneled basement V. new carpet VI. Asking Price: $120K
34
Copyright @ 1999 costello34 Problem Suppose that you are writing a book. The book has chapters. Chapters have sections. Sections have subsections. Suppose that each level has a title, and we would like to number the titles, based upon its level within the document: Chapter 1 Section 1 Subsection 1 1. Chapter 1 1.1 Section 1 1.1.1 Subsection 1 How would you generate this nesting-level-specific numbering using xsl:number?
35
Copyright @ 1999 costello35 Problem Solution Here’s what we want (in pseudocode): for each level (starting with the topmost level), get its level number, append “.” Now append my number to this string of number-periods chapter/title section/title subsection/title 1 1.1 1.1.11.1.2 1.2 1.2.1
36
Copyright @ 1999 costello36 Use the count attribute to indicate the nodes that are relevant in the hierarchy. Use the level attribute to indicate how far up the ancestor chain we should go. count, level attributes of xsl:number.
37
Copyright @ 1999 costello37. “Hey XSL Processor, use this template rule when you encounter a title element in the XML document. When you encounter a title element, here’s what I want you to do. Generate a number as follows: go up my ancestor chain. Whenever a node in the ancestor chain is encountered that is one that is listed in count, get its number (relative to its siblings) and append it to its ancestor’s number.” For those who know Java: public String generateNumber(NodeList ancestorChain) { if (ancestorChain.empty()) return “”; currentNode = ancestorChain.lastNode(); ancestorChainMinusOne = ancestorChain.substring(0, length()-1); if (currentNode.elementOf(count)) { // is the currentNode one of the nodes listed in the count attribute? currentNodeNumber = position(); return generateNumber(ancestorChainMinusOne) + currentNodeNumber; } else return generateNumber(ancestorChainMinusOne); } See Book.xml, Book.xsl for a complete example of this topic.
38
Copyright @ 1999 costello38 level attribute of xsl:number Here are the possible values of the level attribute: –single: create a number at each level based upon the position relative its siblings at that level –multiple: create a number based upon its level in the ancestor chain and its position relevative to its siblings at that level –any: create a number by taking all the nodes and numbering them sequentially These are best understood with examples: chapter/title section/title subsection/title 1 1 12 2 1
39
Copyright @ 1999 costello39 level attribute of xsl:number chapter/title section/title subsection/title 1 2 34 5 6 chapter/title section/title subsection/title 1 1.1 1.1.11.1.2 1.2 1.2.1
40
Copyright @ 1999 costello40 xsl:comment This element gives you the ability to create comments. apple Fruits.xml newFruits.xml XSL?
41
Copyright @ 1999 costello41 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> Fruits.xsl
42
Copyright @ 1999 costello42 name() function This function returns the name of the node specified in the parenthesis. If you specify a list of nodes, it returns the name of the first node. [contents of element] This template rule matches on any element. It then creates an element whose name is the name of the element currently being processed. Note: you need to enclose name(.) within curly braces, otherwise xsl:element will try to interpret it as a node.
43
Copyright @ 1999 costello43 translate() function translate(string, from-pattern, to-pattern) Example. translate(“Hello”, “ABCDEFGHIJKLMNOPQRSTUVWXYZ”, “abcdefghijklmnopqrstuvwxyz”); this will convert Hello to hello (i.e., convert to lower case) A better approach to the above problem is: translate(“Hello”, $upperCaseChars, $lowerCaseChars) Note: need to put the string within quotes, otherwise it will try to interpret it as a node.
44
Copyright @ 1999 costello44 Example Write a stylesheet which converts any XML document to lower case. That is, it converts the elements, attributes, and text to lower case. (It leaves comments and PIs alone.)
45
Copyright @ 1999 costello45 toLowerCase.xsl Thanks to Keith Visco for this solution!
46
Copyright @ 1999 costello46 mode Attribute Allows you to create multiple template rules for the same element. Each template rule can process the element differently.
47
Copyright @ 1999 costello47 Example Suppose that we have an XML document that contains a list of authors, including names and companies. Create a stylesheet that processes the info about the authors in two ways: (1) put the author info in a table, and (2) put the author info in a footnote section.
48
Copyright @ 1999 costello48 Roger L. Costello The MITRE Corporation Keith E. Visco Ex Office James J. Garriss The MITRE Corporation Name Company Roger L. Costello The MITRE Corporation Keith E. Visco Ex Office James J. Garriss The MITRE Corporation [Footnote] 1. Roger L. Costello, The MITRE Corporation 2. Keith E. Visco, Ex Office 3. James J. Garriss, The MITRE Corporation modeExample.xml modeExample.html Note how we will need an author template rule for generating the table, and another author template rule for generating the footnote.
49
Copyright @ 1999 costello49 XSL by Example... Author Info NAME COMPANY [Footnotes]., Two different ways to process the author elements.
50
Copyright @ 1999 costello50 document( ) Function This function enables you to access other XML documents (besides the XML document that you specify when you invoke the XSL Processor). HTML, Text, XML XSL (presentation) XSL Processo r XML (content)
51
Copyright @ 1999 costello51 document( ) Function The format for using the document() function is: document(url), where url is a URL to another XML document Example: Now bookcat2 references the node tree for BookCatalogue2.xml bookcat2 / BookCatalogue Book Title Author Date ISBN Publisher
52
Copyright @ 1999 costello52 Problem Someone just created another BookCatalogue XML document. Write an XSL stylesheet which prints out all the book titles from BookCatalogue.xml and BookCatalogue2.xml
53
Copyright @ 1999 costello53 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> BookCatalogue9.xsl
54
Copyright @ 1999 costello54 When to use Curly Braces? “When I assign an attribute a value, when do I use curly braces and when do I not use them?” Use curly braces for these attributes: - the attribute of a literal result element (where you literally type what should be output) Example: - the name attribute of xsl:attribute Example: - the name attribute of xsl:pi Example: - the name attribute of xsl:element Example: - the optional attributes of xsl:sort: Example: lang =“{@ value}”> data-type =“{@ value}”> case-order =“{@ value}”>
55
Copyright @ 1999 costello55 result tree fragments A result tree fragment is simply a portion of an XML document. The fragment may not necessarily be a complete, well-formed XML document. The only operations on a result tree fragment are string() and boolean() Variables which are defined as follows have contents which are result tree fragments [code to create contents of the variable]
56
Copyright @ 1999 costello56 Stylesheet Reuse via xsl:include and xsl:import The elements xsl:include and xsl:import enable you to reuse other stylesheets. These elements are “top-level elements”. This means that they must be immediate children of the xsl:stylesheet element (i.e., they cannot be within a template) The xsl:include element is basically a macro substitution - the element is replaced by the contents of stylesheet it references
57
Copyright @ 1999 costello57 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">...... Replace the xsl:include element with the contents of the referenced stylesheet (i.e., all the children of xsl:stylesheet) toUpperCase.xsl BookCatalogue10.xsl
58
Copyright @ 1999 costello58 xsl:import xsl:import acts just like xsl:include - the stylesheet that it references is macro-substituted. However, there is a difference: –With xsl:include the stuff that is macro-substituted into the stylesheet has the same precedence as the rest of the stylesheet. It is as though you had one stylesheet. –With xsl:import the stuff that is macro-substituted into the stylesheet has lower precedence than the rest of the stylesheet. Also, all xsl:import elements must come first in the stylesheet.
59
Copyright @ 1999 costello59 xsl:import Suppose that stylesheet A imports stylesheet B and then stylesheet C. Stylesheet B imports stylesheet D. Stylesheet C imports stylesheet E. Draw a tree diagram of the importing. The precedence is determined by a postorder traversal of the tree. A B C D E Postorder traversal (left, right, root): B, D, E, C, A increasing precedence (i.e., the template rules in A have greater precedence than the template rules in C, etc.)
60
Copyright @ 1999 costello60 xsl:key (Motivation) The ID mechanism in XML is rather constraining. Namely, the unique id must be an attribute, not an element value, an element can have at most one attribute, etc. Consequently, people often create their own cross-reference structure, not using ID, IDREF, IDREFS
61
Copyright @ 1999 costello61 P.M. My Life and Times Paul McCartney July, 1998 94303-12021-43892 McMillin Publishing xxx R.B. Illusions The Adventures of a Reluctant Messiah Richard Bach 1977 0-440-34319-4 Dell Publishing Co.... Growing up in Manchester, England during the 60's... There was a Master come unto the earth, born in the holy land of Indiana, raised in the mystical hills east of Fort Wayne... To communicate with one another, even if we know each other very well, is extremely difficult. I may use words that may have to you a significance different from mine. Understanding comes when we, you and I, meet on the same level at the same time... Note that this XML document contains a cross-reference structure that does not use the ID, IDREF, IDREFS datatypes that XML provides
62
Copyright @ 1999 costello62 xsl:key The xsl:key element enables us to declare “hey, the contents of the element is a unique identifier” and “hey, the id attribute of is a unique identifier”. “Hey XSL Processor, I hereby declare that the id attributes of the Intro elements are unique. I will refer to this set of keys by the name ‘contentsKey’”. “Hey XSL Processor, I hereby declare that the text in the key elements are unique. I will refer to this set of keys by the name ‘indexKey’”.
63
Copyright @ 1999 costello63 key() function The key() function is the same as the id() function, except the key() function returns nodes with unique values defined by the xsl:key element. key(‘contentsKey’, ‘R.B.’) selects the Intro element whose key is ‘R.B.’
64
Copyright @ 1999 costello64 Long Notation Thus far we have used the abbreviated notation for expressing a path to a node. There are some things for which it is inadequate –Example. How do you select all ancestor nodes using the abbreviated syntax? You can’t.
65
Copyright @ 1999 costello65 Document / PI DocumentType Element BookCatalogue Element Book Element Book Element Book Element Title Element Author Element Date Element ISBN Element Publisher... Text My Life... Text Paul McCartney Text July, 1998 Text 94303-12021-43892 Text McMillin Publishing ancestors preceeding sibling following siblings If we are currently at the second Book’s Author element then: we can select all ancestors by: all preceeding siblings by: all following siblings by: ancestor::* preceeding-sibling::* following-sibling::* Which yields: Which yields: Which yields: BookCatalogue Title Date Book ISBN Publisher
66
Copyright @ 1999 costello66 Document / PI DocumentType Element BookCatalogue Element Book Element Book Element Book Element Title Element Author Element Date Element ISBN Element Publisher... Text My Life... Text Paul McCartney Text July, 1998 Text 94303-12021-43892 Text McMillin Publishing If we are currently at the second Book element then: we can select all descendants by: descendant::* Which yields: Title Author Date, ISBN, Publisher descendants Note: see BookCatalogue12.xsl for sample code.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.