Introduction to XSL and XSLT

Source: Internet
Author: User
Tags xsl xsl file xslt
Role of XSL: Convert XML into HTML
The following is a part of the XML document:
<? XML version = "1.0" encoding = "ISO8859-1"?>
<Catalog>
<Cd>
<Title> empire burlesque </title>
<Artist> Bob Dylan </artist>
<Country> USA </country>
<Company> Columbia </company>
<Price> 10.90 </price>
<Year> 1985 </year>
</Cd>
...
</CATALOG>
Then, we use the following XSL file as an HTML template to convert XML data to an HTML file:
<? XML version = '1. 0'?>
<XSL: stylesheet xmlns: XSL = "http://www.w3.org/TR/WD-xsl">
<XSL: template match = "/">
<HTML>
<Body>
<Table border = "2" bgcolor = "yellow">
<Tr>
<TH> title </Th>
<TH> artist </Th>
</Tr>
<XSL: For-each select = "catalog/CD">
<Tr>
<TD> <XSL: value-of select = "title"/> </TD>
<TD> <XSL: value-of select = "artist"/> </TD>
</Tr>
</XSL: For-each>
</Table>
</Body>
</Html>
</XSL: Template>
</XSL: stylesheet>
In the above Code, the XSL: For-each element is used to locate which elements in the XML document need to be displayed according to the following template. The select attribute is used to define the element name in the source file. This syntax for specifying attributes is also called XML pattern (pattern), which is similar to the representation of file subdirectories. The XSL: value-of element is used to insert the content template of child elements in the current level.
Because the XSL style sheet itself is also an XML document, the beginning of the XSL file begins with an XML declaration. XSL: the stylesheet element is used to declare that this is a style sheet file. <XSL: Template
Match = "/"> statement indicates that the XML source file is in the current directory.
If you add an XSL style table to an XML document, you can see the following code in line 2. Your browser can accurately convert the XML document to an HTML file.
<? XML version = "1.0" encoding = "ISO8859-1"?>
<? XML-stylesheet type = "text/XSL" href = "cd_catalog.xsl"?>
<Catalog>
<Cd>
<Title> empire burlesque </title>
<Artist> Bob Dylan </artist>
<Country> USA </country>
<Company> Columbia </company>
<Price> 10.90 </price>
<Year> 1985 </year>
</Cd>
...
</CATALOG>
XSL Index
When an XML document is converted to an HTML file, the index should be created at the same time. The simple method is to add an order-by attribute to your for-each element, as shown in the following figure:
<XSL: For-each select = "catalog/CD" Order-by = "+ artist">
The Order-by attribute carries a "+" or "-" symbol to define the index method, in ascending or descending order. The name after the symbol is the keyword to be indexed.
XSL filtering and query
What should we do if we want to display only XML data that meets certain conditions? In the preceding example code, we only need to add parameters to the select attribute of the XSL: For-each element. For example:
<XSL: For-each select = "catalog/CD [artist = 'Bob dylan']">
The logical options of parameters include:
= (Equal)
=! (Not equal)
<& Less
> & Greater than or equal
 
XSL control statement
1. conditional statement if... then
XSL also has conditional statements (haha ~~ It's amazing, like programming languages ). The specific syntax is to add an XSL: If element, similar to this
<XSL: If match = ". [artist = 'Bob dylan']">
... Some output...
</XSL: If>
2. Choose of XSL
The purpose of choose is to display different results when multiple conditions exist. The specific syntax is to add a set of XSL: Choose, XSL: When, XSL: otherwise elements:
<XSL: Choose>
<XSL: When match = ". [artist = 'Bob dylan']">
... Some code...
</XSL: When>
<XSL: otherwise>
... Some code ....
</XSL: otherwise>
</XSL: Choose>
 
XSLT
XSL and XSLT are the same in a narrow sense. According to W3C standards, XSLT is more strict.
In fact, many of them are repeated with the above XSL, but the following explanations are more detailed.
Element Syntax of XSLT
1 XSL: Template and XSL: Apply-templates
Template is one of the most important concepts in XSLT. An XSLT file is composed of one template. Any XSLT file contains at least one template. A template consists of two parts: Match pattern and execution. The simple mode defines which node in the XML source document will be processed by the template, and the execution defines the output format. The syntax of the two parts is XSL: Template and XSL: Apply-templates.
The syntax of XSL: Template is:
<XSL: Template
Match = Pattern
Name = QNAME
Priority = Number
Mode = QNAME>
<! -- Execution content -->
</XSL: Template>
XSL: Template defines a new template. The name, priority, and mode in the attribute are used to distinguish different templates matching the same node. The match attribute controls the pattern of the template. The pattern is used to locate which node in the XML source document is processed by the template. A template matches a node. Let's use an example to help us understand:
Suppose we want to process a section document that contains chapters and paragraphs. We use the Para element to define paragraphs and the chapter element to define chapters. Let's take a look at the possible values of the match attribute. The following statement describes that the template matches all the Para elements.
<XSL: template match = "para">
</XSL: Template>
The following statement describes that the template matches all para elements and all Chapter elements:
<XSL: template match = "(chapterpara)">
</XSL: Template>
The following statement indicates that the template matches all the Para elements whose parent nodes are Chapter elements:
<XSL: template match = "Chapter // para">
</XSL: Template>
The following statement describes that the template matches the root node:
<XSL: template match = "/">
</XSL: Template>
Apply-templates Syntax:
<XSL: Apply-templates
Select = node set-expression
Mode = QNAME>
</XSL: Apply-templates>
XSL: Apply-templates is used to execute the node to be processed by the template. You can understand it as calling subfunctions in a program. The select attribute defines the exact node name. XSL: Apply-templates is always included in the XSL: Template element, like this:
<XSL: template match = "/">
<XSL: Apply-templates select = "para"/>
</XSL: Template>
This code example matches the entire document (root node) and processes all the Para elements under the root node during execution.
<XSL: template match = "para">
<P> <XSL: Apply-templates/> </P>
</XSL: Template>
This Code indicates that the touchpad matches the Para node, and all child elements under para are processed.
XSL: value-
XSL: value-of is used to write the text values of elements in the source document to the output document. For example:
There is an XML document for personal data:
<? XML version = "1.0" encoding = "iso-8859-1"?>
<Person>
<Name> Ajie </Name>
<Age> 28 </age>
</Person>
If you want to display the name element value in the above XML source document in the output document, you can write the XSLT Code as follows:
<XSL: template match = "person">
<XSL: value-of select = "name"/>
</XSL: Template>
After execution, you will see that "Ajie" is displayed separately. The match = "person" defines the pattern that matches the person node. The XSL: value-of syntax indicates that the value of a node needs to be output, select = "name" defines the element to be output as name. Check whether this process is similar to querying a person's name in the database? Of course, there are more and more complex syntaxes for XSL: value-of queries. because it involves the searching and locating functions, we will explain them carefully in the later XPath syntax.
The same functions include XSL: copy-of. If the usage is the same, it will not be repeated.
XSL: For-each
XSL: For-each syntax allows you to process selected nodes cyclically. For example, there is an XML document containing multiple personal data:
<? XML version = "1.0" encoding = "iso-8859-1"?>
<People>
<Person>
<Name> Ajie </Name>
<Age> 28 </age>
</Person>
<Person>
<Name> Tom </Name>
<Age> 24 </age>
</Person>
..............
</People>
To display the names of all people, you can write the XSLT Code as follows:
<XSL: template match = "people">
<XSL: For-each select = "Child: Person">
<XSL: value-of select = "name"/>
</XSL: For-each>
</XSL: Template>
 
XSL: If
XSL: If is similar to the IF Condition Statement in common programming languages. If a node can be set to meet a certain condition, it is processed by a template. The syntax format of XSL: If is:
<XSL: If test = Boolean expression>
Template body
</XSL: If>
As follows:
<XSL: template match = "people">
<XSL: If test = "@ name">
<P> <XSL: value-of select = "@ name"/> </P>
</XSL: If>
</XSL: Template>
This code detects all elements under the People node. If a <Name> element is found, the value of the <Name> element is output. The @ symbol indicates all elements under the node.
XSL: Choose, XSL: When and XSL: otherwise
XSL: The if syntax does not have the attributes of else. If you want to make multiple choices, you need to use the XSL: Choose/XSL: When/XSL: otherwise series process control syntax. For specific usage, see the following XSL file example:
<XSL: template match = "people">
<XSL: Choose>
<XSL: When test = "@ name = 'ajie '">
<B> <XSL: value-of select = "@ name"/> </B>
</XSL: When>
<XSL: When test = "@ name">
<I> <XSL: value-of select = "@ name"/> </I>
</XSL: When>
<XSL: otherwise>
No name available
</XSL: otherwise>
<XSL: Choose>
</XSL: Template>
Note: First, find the elements whose <Name> attribute value is Ajie under the People node. If yes, output Ajie in bold. If no <Name> element whose value is Ajie is found, all <Name> element values are output in italic. If no <Name> element is found, "No Name available" is displayed ".
XSL: Sort
In XSLT, elements of the XML source document can be re-ordered. The sorting syntax is XSL: sort. For example, the following code sorts document elements by name.
<XSL: template match = "people">
<XSL: Apply-templates select = "person">
<XSL: Sort select = "@ name"/>
</XSL: Apply-templates>
</XSL: Template>
 
XPath syntax
1. Current location
When we use XSLT to process XML source documents, we use context to represent the node location currently being processed by the template. For example, in the XSL: template match = "/" Statement, context indicates the root node of the document. I don't know how to accurately translate the term context. It is similar to a pointer in C language, indicating the current position of the program. Understanding context is very important for correct processing of the XSL template. When the document output by your XSL template is different from what you want, the first thing to analyze is where the context is.
Location paths is used to set the location of the context node you want to find. It is similar to the DOS directory command. Let's look at an example.
<XSL: For-each select = "Child: People/descendant: Person">
Child: People/descendant: person is the XPath syntax, and this expression is a location paths. The code description shows the child elements of all people elements and the child elements of all person elements. We usually adopt a simpler method:
<XSL: For-each select = "People/person">
We will explain two methods of path representation: "/" and "//".
"/" Indicates the node of the current document, similar to the DOS directory delimiter. For example,/People indicates selecting the people element under the root node; people/person indicates Selecting All the peson sub-elements under the People element.
"//" Indicates all nodes in the current document. Similar to viewing the entire directory. For example, // People indicates to select all the people elements in the document, no matter what level it is. People // person indicates all the person elements under the People element, no matter how deep it is.
2 addressing operations
Axis and predicate are the syntax for locating location paths in XPath syntax. The specific usage list is as follows:
Axis syntax table
--------------------------------------------------------
Abbreviated expression description
--------------------------------------------------------
Self. Select the current node ..
Example:
<TD> <XSL: value-of select = "."/> </TD>
The Code inserts the text value of the current node at the current position,
--------------------------------------------------------
Parent .. select the parent node of the current node.
--------------------------------------------------------
Attribute @ select all attributes of an element.
Example:
<TD> <XSL: value-of select = "@ personid"/> </TD>
Select all attributes of the person element.
--------------------------------------------------------
Child Selects all child elements of the current node.
--------------------------------------------------------
Ancestor Selects all the parent elements of the current node (including the parent element of the parent element, and so on)
--------------------------------------------------------
Axis helps us select all nodes around the current node, while predicate is used to locate the elements inside the current node. The expression in [] is [expression] in square brackets. For example:
Person [position () = 2] indicates searching for the second "person" element.
Person [starts-with (name, "B")] indicates searching for all the person elements whose names start with "B.
3 OPERATOR
This section describes the XPath operators (expressions). The list is as follows:
--------------------------------------------------------
Operator description
--------------------------------------------------------
And, or is the common meaning and, or
--------------------------------------------------------
= Equal
--------------------------------------------------------
! = Not equal
--------------------------------------------------------
>,>= Greater than, greater than or equal
--------------------------------------------------------
<, <= Less than, less than or equal. Note: In the XSL file, the <symbol must be expressed as <
--------------------------------------------------------
+,-, *, Div addition, subtraction, multiplication, division
--------------------------------------------------------
MoD modulo
--------------------------------------------------------
Computing with two nodes
--------------------------------------------------------
4. Functions)
Many functions in XPath can help us find the desired node precisely.
Count ()
Purpose: count the number of nodes that meet the condition.
Example: <p> <XSL: value-of select = "count (person [name = Tom])"/> </P>
Note: The purpose of the code is to display the number of Tom attributes in the person element.
Number () function
Purpose: Convert the text in the attribute value to a value.
Example: <p> The number is: <XSL: value-of select = "number (book/price)"/> </P>
Note: The purpose of the code is to display the book price.
Substring ()
Syntax: substring (value, start, length)
Purpose: intercept a string.
Example: <p> <XSL: value-of select = "substring (name, 1, 3)"/> </P>
Note: The purpose of the code is to take the value of the name element and display it from the first letter to the third.
Sum () function
Purpose: sum.
Example: <p> total price = <XSL: value-of select = "sum (// price)"/> </P>
Note: The purpose of the code is to calculate the sum of all prices.
The above functions are only part of the XPath syntax. A large number of functional functions are not introduced yet, and the XPath syntax is still evolving. Through these functions, we can implement more complex queries and operations.

XSLT is a language used to convert XML documents. It contains two processes: conversion and formatting. XSLT is much more powerful than CSS. It has a syntax similar to data query.
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.