Xslt Can We Use Same Value Again
Chapter 7
Transforming XML with XSLT
In this affiliate: XSLT Processing Mechanics
Single-Template Stylesheets
Understanding Input and Output Options
Improving Flexibility with Multiple Templates
Nosotros've used XSLT stylesheets in previous chapters to transform database-driven XML into HTML pages, XML datagrams of a particular vocabulary, SQL scripts, emails, and and then on. If you're a developer trying to harness your database data to maximum advantage on the Web, y'all'll find that XSLT is the Swiss Army knife you want permanently fastened to your chugalug. In a world where the exchange of structured information is core to your success, and where the power to quickly evolve and repurpose data is paramount, Oracle XML developers who fully understand how to exploit XSLT are way ahead of the pack.
XSLT 1.0 is the W3C standard language for describing transformations between XML documents. Information technology is closely aligned with the companion XPath 1.0 standard and works in concert with information technology. As we'll see in this chapter, XPath let'south yous say what to transform, and XSLT provides the complementary linguistic communication describing how to carry out the transformation. An XSLT stylesheet describes a set of rules for transforming a source XML certificate into a result XML document. An XSLT processor is the software that carries out the transformation based on these rules.
In the unproblematic examples in previous chapters, we accept seen three primary ways to use the Oracle XSLT processor. We've used the oraxsl control-line utility, the XSLT processor'southward programmatic API, and the <?xml-stylesheet?> instruction to associate a stylesheet with an XSQL page. In this chapter, we begin exploring the full ability of the XSLT language to sympathize how best to employ it in our applications.
XSLT Processing Mechanics
An XSLT stylesheet describes a transformation that operates on the tree-structured infoset of a source XML document and produces a tree of nodes every bit its output.
Consider a elementary XML document like this:
<!-- Emp.xml --><ROWSET><ROW num="ane"><EMPNO>7839</EMPNO><ENAME>KING</ENAME></ROW><ROW num="ii"><EMPNO>7788</EMPNO><ENAME>SCOTT</ENAME></ROW></ROWSET>
A transformation of this document operates on the document'southward respective node tree (shown in Effigy seven-i). The tree of nodes for an XML document always starts with a root node that represents the document itself. Kid nodes of the root can exist the single document element node--<ROWSET>, in our case--also as comments and processing instructions. Child nodes of the document element can be any combination of text nodes and element nodes, each of which may, in turn, have similar kid nodes. This nesting of nodes forms a tree.
| |
TIP:
Remember that an XML certificate tin look like this:
<ROWSET> <ROW num="1"> <Ten>Y</Ten> </ROW> </ROWSET> or it tin look similar this:
<ROWSET><ROW num="1"><X>Y</X></ROW></ROWSET> NOTE: While both expressions contain a logically equivalent element structure, the erstwhile example contains additional whitespace (denoted by
WSnodes in Effigy vii-1) to give information technology that indented look. Specifically, information technology contains a carriage return at the end of every line followed past a series of spaces at the start of the next line. When considering an XML document as a tree of nodes, don't forget that the text nodes containing whitespace likewise count as nodes the same every bit text like7788orSCOTT. Since you tin't see information technology, whitespace is easy to forget nearly.
To carry out a transformation, an XSLT processor requires two ingredients:
- The source tree of nodes
- An XSLT stylesheet containing a set of transformation rules
An XSLT stylesheet is an XML certificate that uses elements from the XSLT vocabulary to describe a transformation. The document element of every stylesheet is an <xsl:stylesheet> element whose content is a set of rules describing the transformation to be performed. Each dominion in the stylesheet contains an associated XPath blueprint that matches the nodes in the source document to which that dominion should utilize. Each rule is called a template and is represented by an <xsl:template> element with a match=" blueprint " attribute for its associated XPath match pattern. For example, a rule like this:
<xsl:template match="/"><!-- Some Effect Content: Elements, Attributes, Text, etc. --></xsl:template>
applies to the root node of the document, matching the XPath pattern "/".
Similarly, a dominion like this:
<xsl:template match="ROWSET/ROW[ENAME]"><!-- Some Outcome Content: Elements, Attributes, Text, etc. --></xsl:template>
applies only to <ROW> elements in the source document that have an <ENAME> child element and occur every bit immediate children of a <ROWSET> chemical element.
Each dominion is chosen a template because the literal elements and attributes contained inside the body of the rule human action as a blueprint for constructing a role of the effect tree. The XSLT processor constructs the content of a rule's template in the event tree whenever it processes a source node matching the rule's pattern. Figure 7-2 illustrates what happens when a rule like this:
<xsl:template friction match="ROWSET/ROW[ENAME]"><Employee id="NX-{EMPNO}"><xsl:value-of select="ENAME"/></Employee></xsl:template>
is triggered by processing a <ROW> element in the source tree that matches the XPath pattern ROWSET/ROW[ENAME].
| |
As the matching template is instantiated, the following three things occur:
- Literal event elements and attributes in the template are created in the result tree. Result elements and attributes that are not from the XSLT namespace are considered "literal" since they are constructed as is in the event tree. In the instance just given, the <Employee> chemical element and its
idattribute are created. - Any attribute value templates of the class
{XPathExpr}contained within literal aspect values are replaced by the value of their XPath expression. In the example, the{EMPNO}inside the literal attribute valueNX-{EMPNO}is replaced past the value of theEMPNOXPath expression. This evaluates to7839, and so the terminal value for theidattribute in the upshot tree isNX-7839. - Any elements in the XSLT namespace are processed in document order. The <xsl:value-of> element is processed and is replaced past a text node containing the string value of the XPath expression in its
selectattribute--in this example,King.
The bones operation tin can be summarized as follows: when a node in the source matches a rule's pattern, the content of that rule is created in the result tree. One time you grasp this basic functioning, the overall XSLT processing model is easy to understand. Given a source tree and a stylesheet, the XSLT processor carries out the transformation described by rules in the stylesheet by following a sequence of steps, but like the ones we have described.
A list of nodes in the source tree is processed to create a portion, or "fragment," of the consequence tree. The event tree fragment for the listing of nodes is created by processing the nodes in order and concatenating each of their corresponding result tree fragments together in the same order. The node in the current node list existence processed is known, not surprisingly, every bit the current node. The electric current node is candy by considering the set of all possible rules that friction match information technology then selecting the single rule that matches it all-time. But a single dominion is ever used to procedure the current node in the electric current node list.
To offset the process, the XSLT processor begins with a node list containing only the document root. Information technology finds the template matching this root node--typically the rule with match="/"--and instantiates the contents of the template in the consequence tree, following the three bones processing steps to consummate the job. If the template contains elements from the XSLT namespace that select other nodes to process, the sequence of matching and template content instantiation continues recursively until there are no nodes left to procedure. When processing is completed, the result tree represents the target document produced by the transformation.
Single-Template Stylesheets
Many useful transformations can be expressed with just a single-root template. We'll examine the single-template stylesheet here, only we'll spend the rest of this chapter learning why in that location's a world beyond the root template and why it'south worth learning almost.
All of the stylesheets we've seen so far for transforming XML into HTML either have looked like this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://world wide web.w3.org/1999/XSL/Transform"><!-- The "root" or "main" template --><xsl:template friction match="/"><html><body><!--| Literal consequence elements and attributes, intermingled with| <xsl:for-each>, <xsl:value-of>, attribute value templates, etc.+--></body></html><xsl:template></xsl:stylesheet>
or have used the simple form of the unmarried-root template stylesheet, which looks like this:
<!-- In the "uncomplicated class" of a stylesheet, the root template is implied --><html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><body><!--| Literal upshot elements and attributes, intermingled with| <xsl:for-each>, <xsl:value-of>, aspect value templates, etc.+--></body></html>
TIP:
When y'all run across the
xslnamespace declaration:
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" it is natural to think that the XSLT processor will try to access that URL when your stylesheet is processed. Yet, the declaration is only used as a unique cord to identify the namespace for XSLT. If you exercise not provide this exact string equally the namespace URI for the
xslnamespace prefix, the XSLT processor will simply ignore <xsl:template>, <xsl:for-each>, <xsl:value-of>, and other elements with thexslprefix since it will non recognize them as XSLT actions.
Consider the stylesheet in Case seven-1.
Example 7-1: Single-Root Template Stylesheet to Transform Emp.xml to HTML
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="/"><html><trunk><xsl:for-each select="ROWSET"><table border="i" cellspacing="0"><xsl:for-each select="ROW"><tr><td><xsl:value-of select="EMPNO"/></td><td><xsl:value-of select="ENAME"/></td></tr></xsl:for-each></table></xsl:for-each></body></html></xsl:template></xsl:stylesheet>
This transforms our simple Emp.xml <ROWSET> document into an HTML document with the employee data in a tabular array, as shown in Figure vii-3.
| |
The content of the root template is a mixture of the familiar literal HTML elements <html>, <torso>, <table>, <tr>, and <td>, strategically sprinkled with <xsl:for-each> and <xsl:value-of> elements. When the XSLT processor instantiates the root template, the certificate root node is the current node. The <xsl:for-each> element:
- Selects a list of source tree nodes to process
- Makes this list of selected nodes the current node list
- Begins processing the nodes in the electric current node listing in order
The content of the <xsl:for-each> chemical element is instantiated in the result tree for each node in the current node listing. The content of this instantiated result tree fragment is processed (with respect to the current node) for additional XSLT elements, if any.
Any <xsl:value-of> elements encountered in the instantiated issue tree fragments are replaced by the string value of the XPath expression in their select attribute. Figure 7-four illustrates the process.
| |
The resulting HTML document is shown in Example 7-2.
Example seven-2: Output of Emp.xml Using Single-Root Template Stylesheet
<html><torso><table border="one" cellspacing="0"><tr><td>7839</td><td>KING</td></tr><tr><td>7788</td><td>SCOTT</td></tr></tabular array></trunk></html>
In this example, the XSLT processor only performs template matching for the root node. All subsequent nodes selected for processing are the result of processing the <xsl:for-each> action'southward select patterns and iterating over the node-sets they render.
If a stylesheet uses only the root template, and then it tin optionally utilize the simple-class stylesheet syntax that allows <xsl:stylesheet> and <xsl:template match="/"> to be left out. In this case, the literal chemical element that would take been the starting time element in the root template is instead the first chemical element of the unabridged stylesheet. Yous must include the namespace announcement for the XSLT namespace on the literal result element that is at present the document chemical element of the stylesheet document, besides as add the namespace-qualified xsl:version="1.0" attribute to the element:
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><body><xsl:for-each select="ROWSET"><table border="1" cellspacing="0"><xsl:for-each select="ROW"><tr><td><xsl:value-of select="EMPNO"/></td><td><xsl:value-of select="ENAME"/></td></tr></xsl:for-each></table></xsl:for-each></body></html>
This produces the aforementioned results as the stylesheet with normal syntax we saw earlier.
Understanding Input and Output Options
The XSLT transformation process described before was explained in terms of node trees. These trees of nodes are the logical course that both the source and consequence of a transformation can take on the "inside" of a transformation being performed by an XSLT processor. However, this is what happens on the outside:
- The source document typically begins as a stream of man-readable characters.
- The event of the transformation typically needs to be written out every bit another stream of homo-readable characters--for example, to send the result dorsum to a requesting browser or to salvage the result in a file for later.
The input to an XSLT transformation must exist a tree of source nodes produced by either parsing a well-formed XML certificate or creating the tree programmatically (for instance, via DOM or SAX APIs).
All XSLT transformations procedure the source node tree to produce a tree of outcome nodes. If multiple transformations are being practical in sequence by your application, the event tree of one transformation becomes the source tree of the next transformation in sequence. When no more transformations demand to be done, the final tree of upshot nodes needs to exist written out as a stream of characters again. This process is called serializing the result tree.
Unproblematic-form stylesheets have advantage of default serialization rules described by the XSLT 1.0 specification to make common cases simple. They serialize transformed output in the default UTF-eight character gear up and back up either of the following output formats:
- Indented, properly formatted HTML output, with a media type of
text/html - Non-indented XML output with no
DOCTYPEand a media type oftext/xml
Going beyond these defaults requires using the more verbose, standard XSLT stylesheet syntax that begins with an <xsl:stylesheet> element that includes every bit a directly child an <xsl:output> element, which offers command over the serialization procedure.
The well-nigh of import serialization control to empathise is the output method. This governs the bones rules that the XSLT processor will use when serializing the result tree nodes to an output stream. XSLT 1.0 supports 3 different output methods:
-
<xsl:output method="xml"/> - This method is the default and outputs the nodes likewise-formed XML.
-
<xsl:output method="html"/> - This method is the default for upshot trees whose document element is <html>, <HTML>, or whatsoever case-variation in between. It serializes elements and attributes in an HTML iv.0-friendly way that ensures existing browsers will recognize it. In item, it does not write out well-formed XML.
-
<xsl:output method="text"/> - This method outputs only the text nodes in the result tree in document order. It is used for transforming XML into programming linguistic communication source files, emails, or other plain text output.
Consider the following example source certificate:
<!-- King.xml --><ROWSET><ROW><EMPNO>7839</EMPNO><ENAME>KING</ENAME></ROW></ROWSET>
The following stylesheet uses the xml output method to transform this King.xml <ROWSET> certificate into an <Invitation> document:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="xml" indent="yes"/><xsl:template match="/"><Invitation><To><xsl:value-of select="ROWSET/ROW/ENAME"/><xsl:text> & Family</xsl:text></To></Invitation></xsl:template></xsl:stylesheet>
Transforming King.xml using this stylesheet produces the following consequence:
<?xml version="one.0"?><Invitation><To>King & Family</To></Invitation>
TIP:
Remember that XSLT stylesheets are well-formed XML documents, so characters that need to be escaped (like
&and<) must be escaped with&and<in your stylesheets, too. While the>entity exists to escape the>character, its apply is optional. Finally, notation that a numerical character entity similar&tin can exist used as an alternative to represent the character whose Unicode number in decimal is 38, which is the ampersand, and some processors choose to emit all reserved characters using this numerical approach. In your own stylesheets, if y'all are more comfortable with hexadecimal, you tin use a hexadecimal numerical entity as well. For example, a carriage render, Unicode number ten or 0A in hex, can exist represented alternatively as&#x;using decimal or
using hex.
The following stylesheet uses the html output method and transforms the <ROWSET> document into a simple HTML folio with a paragraph tag and an paradigm:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="html"/><xsl:template lucifer="/"><html><trunk><p><xsl:value-of select="ROWSET/ROW/ENAME"/><xsl:text> & Family unit</xsl:text></p><img src="images/{ROWSET/ROW/EMPNO}.gif"/></body></html></xsl:template></xsl:stylesheet>
Transforming Male monarch.xml using this stylesheet produces the following result:
<html><body><p>KING & Family</p><img src="images/7839.gif"></body></html>
Finally, this third example stylesheet uses the text output method to transform the <ROWSET> certificate into plain text output with no markup tags:
<xsl:stylesheet version="1.0" xmlns:xsl="http://world wide web.w3.org/1999/XSL/Transform"><xsl:output method="text"/><xsl:template friction match="/"><xsl:text>How-do-you-do </xsl:text><xsl:value-of select="ROWSET/ROW/ENAME"/><xsl:text> & Family,
</xsl:text><xsl:text>Your id is </xsl:text><xsl:value-of select="ROWSET/ROW/EMPNO"/></xsl:template></xsl:stylesheet>
This produces the effect:
Hello King & Family unit,Your id is 7839
Note that we're using <xsl:text> elements to include literal text in the issue of the transformation. In general, whitespace is ignored in the stylesheet certificate, so tags can exist nicely indented for readability. However, the whitespace inside of <xsl:text> elements is respected, then we use <xsl:text> when we desire precise control over the whitespace that gets created in the resulting document. Literal spaces, tabs, and carriage returns included in <xsl:text> elements are included verbatim in the upshot. Note the use of &x0A; to correspond the literal railroad vehicle return in the result.
Figure vii-5 illustrates the source certificate, source node tree, result node trees, and final serialization of the previous three transformations, abiding by each transformation'due south specified output method.
| |
In addition to the output method, several other interesting serialization hints tin be specified on the <xsl:output> chemical element in a stylesheet. Tabular array 7-1 summarizes the <xsl:output> settings that come in handy most frequently.
| If target document needs | Set this <xsl:output> attribute |
|---|---|
| Raw text output | |
| HTML output | |
| XML output | |
| Character fix encoding ENC | |
| System Identifier URI | |
| PUBLIC Identifier URI | |
| Beautifying whitespace added | |
| No additional whitespace added | |
| MIME/Media Type of TYP | |
With the fundamentals of single-root template transformations and their about common serialization options now nether our belts, let'due south motility on to understand why developers ever bother to use more than than merely a single-root template.
Improving Flexibility with Multiple Templates
Every bit nosotros've learned, a stylesheet is a set of rules. When you utilise only a single-root template, your stylesheet has, accordingly, just a single rule: "When yous see the root of the source document, exercise everything within this!"
As we'll acquire in this section, this strategy has pros and cons similar to those of adopting an "everything in a single main( ) method" coding manner in Java:
public grade doit {public static void primary( ) (String[] args) {// When this program runs, do everything inside this!}}
Developers learning Java notice it like shooting fish in a barrel to start with this simple approach, but they rapidly detect themselves writing repetitive code that would exist nice to factor into helper methods. When this occurs, they would like to stand on the shoulders of other developers by extending others' existing work, overriding just the methods that need to comport differently.
We'll run into that there is a squeamish conceptual analogy between methods in Java classes and templates in XSLT stylesheets. In Java, methods are both the unit of behavior and the unit of overriding. If you write a class with all of the programming logic in a single main( ) method, and so someone extending your form can only override that single main( ) method. This ways they have to rewrite all the logic but to change one small behavioral aspect. The more effectively a class's methods are logically factored to correspond the set of subtasks the class must perform, the easier it is to reuse a unmarried useful method when appropriate, and the easier it is to override simply a part of the existing beliefs, if necessary.
In XSLT, templates are the unit of behavior likewise equally the unit of overriding. Similar to the Java analogy to a higher place, if you write a stylesheet with all of the transformation logic in a single-root template, so someone extending your stylesheet tin just override that entire template to change the manner your transformation behaves. The more than effectively a stylesheet's templates are logically factored to reflect the individual transformation tasks to exist performed, the easier it is to reuse a single useful template when appropriate, and the easier it is to override only a part of the existing transformation beliefs, if necessary.
Using Multiple Templates
Instance vii-3 shows what our single-root template stylesheet from the previous section looks like if we factored information technology into multiple templates. We've created a template for each chemical element in the source document that we will run into and nosotros accept fabricated each template responsible for a small role of the transformation task. Each template uses the <xsl:utilise-templates> action to tell the XSLT processor to "carry on processing my children nodes" so recursive processing of the tree tin proceed.
Case 7-3: Simple Stylesheet to Produce HTML Using Multiple Templates
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="one.0"><xsl:output indent="no"/><xsl:template match="/"><html><body><xsl:apply-templates/></body></html></xsl:template><xsl:template friction match="ROWSET"><table edge="one" cellspacing="0"><xsl:apply-templates/></table></xsl:template><xsl:template match="ROW"><tr><xsl:apply-templates/></tr></xsl:template><xsl:template match="EMPNO"><td><xsl:use-templates/></td></xsl:template><xsl:template friction match="ENAME"><td><xsl:utilise-templates/></td></xsl:template></xsl:stylesheet>
The way to read a template that looks like this:
<xsl:template friction match="ROWSET"><tabular array border="1" cellspacing="0"><xsl:apply-templates/></table></xsl:template>
is as follows:
Whenever we match a <ROWSET> element in the source tree, construct a <table> chemical element in the result tree to contain the results of processing the children of the current <ROWSET>, and become process those children at present!
When the XSLT processor encounters an <xsl:utilize-templates> activeness, information technology processes the current node's children and includes whatever event tree fragments constructed past that processing at the location in the event tree where the <xsl:employ-templates> appears. Appropriately, since here <xsl:use-templates> is nested inside the literal <table> result element, the result of processing the children of the electric current <ROWSET> element will be nested inside the <table> chemical element in the result tree.
You tin read the unabridged stylesheet in Instance seven-3 as shown in the following table:
| When we lucifer | Construct |
|---|---|
| The source certificate'southward root " | <html> element and nested <body> element in the event tree to contain the results of processing the document--that is, the children of the root |
| <ROWSET> element | <table> to comprise the results of processing the current <ROWSET>'south kid nodes |
| <ROW> element | <tr> to comprise the results of processing the current <ROW>'s child nodes |
| <EMPNO> chemical element | <td> to incorporate the results of processing the electric current <EMPNO>'s child nodes |
| <ENAME> chemical element | <td> to comprise the results of processing the electric current <ENAME>'s child nodes |
Figure seven-vi illustrates the process that takes place during the transformation.
| |
Equally usual, the processor begins by processing the root node in the source tree and finding a dominion that matches it. Our stylesheet has a match="/" template, then it is instantiated with the root node as the current node. The root template constructs the <html> and <body> elements, and then the <xsl:utilise-templates> is executed to process the list of children of the document root. The listing of children of the root includes ane comment node and one element node, the <ROWSET>. To construct the effect tree fragment for this list of nodes, the processor processes each one in guild. The comment node is ignored (we'll learn why in a infinitesimal) and then the <ROWSET> element is candy by finding a dominion that matches it. Our friction match="ROWSET" template matches, then the processor instantiates it in the result tree. This creates a literal <tabular array> element in the issue tree nested inside the previously instantiated <html> and <body> elements; then <xsl:utilise-templates> is executed to process the list of children of the current <ROWSET> element. The children of the electric current <ROWSET> element are the following four nodes, listed hither in gild:
- Text node containing whitespace
- <ROW> element
- Text node containing whitespace
- <ROW> chemical element
Each node in the current node list is processed by finding a matching template and instantiating it. This has the consequence of copying the whitespace to the result tree and instantiating the content of the match="ROW" template twice to construct two <tr> elements in the result tree. And the process continues.
The result of this transformation is the same as the result of our single-root template stylesheet, just as nosotros'll see in the side by side several examples, having things cleaved into multiple templates makes for a much more powerful image.
Understanding Built-in Templates
Before moving on, nosotros demand to empathise why comments were ignored and how whitespace and the text nodes for 7839, Male monarch, 7788, and SCOTT plant their way into the result tree.
Both of these results occurred based on the following congenital-in templates that are included by the XSLT processor equally role of every stylesheet:
<xsl:template match="/|*"><xsl:apply-templates/></xsl:template><xsl:template match="text( )|@*"><xsl:value-of select="."/></xsl:template><xsl:template friction match="processing-instruction( )|comment( )"/>
The following table shows how to read these templates:
| When nosotros match | Construct |
|---|---|
| The source certificate's root " | Nothing, but continue past processing the children nodes of the current node |
| A text node " | A text node containing the value of the current node, finer copying the text or aspect value to the outcome tree |
| A processing educational activity | Nothing |
These congenital-in rules serve every bit fallbacks to keep the recursive processing going in example the current node is not explicitly matched by any other template in the stylesheet. Their definitions reveal a couple of interesting points:
- A dominion tin can match whatever one of several patterns by using the XPath union operator "
|" between the patterns in itsluciferattribute. - To create a dominion that matches a design and explicitly does nothing--that is, creates no result tree nodes and does not continue processing to its children--just ascertain an empty <xsl:template> node.
To amend sympathize the built-in rules, let's try to transform our elementary Emp.xml certificate using the following stylesheet that contains no <xsl:template> rules:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="ane.0"><!-- This stylesheet contains no rules --></xsl:stylesheet>
Nosotros can employ the oraxsl command-line tool with the control:
oraxsl Emp.xml OnlyBuiltinRules.xsl to become the post-obit event:
<?xml version = 'ane.0' encoding = 'UTF-eight'?>7839KING7788SCOTT
The congenital-in rule for matching elements and the document root keeps the recursion going without constructing any elements in the result tree. Each chemical element that is encountered matches this rule, which immediately says "process the children of the current node." When those children nodes are the text nodes containing whitespace, or the text nodes containing 7839, KING, 7788, and SCOTT, the built-in rule for text( ) is matched, and its default action is to do <xsl:value-of select="."/>, which copies the cord value of the current node--the text node, in this case --to the issue tree. Accordingly, the result tree is merely a pile of all the text nodes in the document at any level, in certificate order. Although this is interesting, and helpful to call back for debugging, we won't likely be putting our empty stylesheet into production apply any time shortly.
Wildcard Matching and Whitespace Handling
Allow'south turn our attention back to the multiple-template stylesheet from Example vii-3. One of the things that should bother yous about it is that both of the following templates:
<xsl:template match="EMPNO"><td><xsl:apply-templates/></td></xsl:template><xsl:template match="ENAME"><td><xsl:utilize-templates/></td></xsl:template>
are doing the same thing. They each match an element that nosotros await to be a child element of the <ROW> and create a table jail cell <td> chemical element to contain the result of processing the children. The following query produced the simple Emp.xml document:
SELECT empno, enameFROM empWHERE ename in ('Male monarch','SCOTT')ORDER BY SAL
Just what if we included all of the columns in the emp tabular array? Would we have to perpetuate these repetitive templates to comprehend each new element, like <SAL>, <COMM>, <DEPTNO>, and so on? We could, but nosotros should showtime getting the feeling that there must exist a better way. Since we want to practise the same thing for every element that occurs as a child of the <ROW>, namely, construct a <td> table jail cell to comprise the effect of processing its children, we can merely utilise XPath to say exactly what we want. The blueprint to match any chemical element that is a child of a <ROW> chemical element is ROW/*. So we can eliminate all of the templates for each individual <ROW> kid element and create a more generic template to the job:
<!-- Match any element child of a ROW --><xsl:template match="ROW/*"><td><xsl:apply-templates/></td></xsl:template>
This leaves us the with the stylesheet in Example 7-four, which is ready to suit futurity expansion in the number of columns by processing any child elements of a <ROW> in a generic mode.
Example 7-4: Stylesheet Using Multiple Templates for ROWSET/ROW Data
<xsl:stylesheet version="one.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><!--| EmpUsingRowStar.xsl:| Transform Emp.xml Into <table> using ROW/* to handle any column+--><xsl:template match="/"><html><body><xsl:utilise-templates/></body></html></xsl:template><xsl:template friction match="ROWSET"><table border="one" cellspacing="0"><xsl:apply-templates/></table></xsl:template><xsl:template match="ROW"><tr><xsl:utilize-templates/></tr></xsl:template><!-- Match any element child of a ROW --><xsl:template match="ROW/*"><td><xsl:use-templates/></td></xsl:template></xsl:stylesheet>
This should produce the same event as before, so permit's try it. Using the command-line oraxsl tool to transform our Emp.xml document using EmpUsingRowStar.xsl with the control:
oraxsl Emp.xml EmpUsingRowStar.xsl We go the output:
<html><trunk><table border="i" cellspacing="0"><tr><td>7839</td><td>King</td></tr><tr><td>7788</td><td>SCOTT</td></tr></tabular array></body></html>
Just expect. This does not look exactly the aforementioned as the nicely indented output we saw in Instance 7-2 using the single-root template stylesheet from Example seven-ane. The indenting of the <tr> elements and closing </table> tag is wrong, for some reason. It's important to understand why, since it relates to how XSLT handles whitespace in the source document. Recall that what makes the Emp.xml document look indented is whitespace characters, like carriage returns and spaces. Figure 7-7 illustrates what the document would look similar if we could encounter these whitespace characters.
| |
When the template matching <ROWSET> is processed in EmpUsingRowStar.xsl, information technology constructs the <table> tag and continues recursive processing of <ROWSET>'s kid nodes with <xsl:employ-templates>. Recall from Effigy 7-i that the first-level child nodes of <ROWSET> are the post-obit, listed here in social club:
- A text node containing the whitespace characters to indent the line: carriage return, space, space
- A <ROW> element
- A text node containing the indentation whitespace characters: carriage return, space, space
- A <ROW> element
Using the multiple-template approach, the XSLT processor processes these child nodes of <ROWSET>, in social club and tries to find templates that match. When processing the first text node child, no explicit templates in EmpUsingRowStar.xsl match this text node, then the built-in template matching "text( )|@*" matches every bit a fallback and performs its born activeness of copying the text to the result tree. There is nothing special virtually how whitespace-only text nodes are handled past the born rule: the characters are merely copied verbatim to the outcome like any text node. These extra carriage returns copied as is into the effect past the built-in template explain why the indenting behavior of the output was slightly disturbed.
It's equally important to understand why our stylesheet in Example 7-1 did not run into this trouble. Using that single-root template stylesheet, the XSLT processor does template matching only for the root node. Afterward this, the only nodes that are processed are the ones explicitly selected past deportment like <xsl:for-each>. Since that stylesheet never explicitly selected any text nodes for processing, the trouble of copying their contents to the result never materialized.
To remedy the situation for EmpUsingRowStar.xsl, we can instruct the XSLT processor to strip, and hence ignore for transformation, whatever text nodes in the source tree that consist entirely of whitespace characters. We can accomplish this by adding an <xsl:strip-space> element to the top level of our stylesheet:
<xsl:stylesheet version="i.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><!--| Strip text node children consisting entirely of whitespace for| all elements in the source document.+--><xsl:strip-space elements="*"/>
The value of the elements attribute of <xsl:strip-space> is a whitespace-separated list of chemical element names whose text node children consist entirely of whitespace you would similar to strip. Using an asterisk (*) strips infinite from all elements. To strip infinite from all merely one or all simply a few elements, yous can use <xsl:strip-infinite> in combination with the companion <xsl:preserve-space> element which takes an analogous elements attribute, listing elements for which y'all want to preserve whitespace. By default, an XSLT processor preserves whitespace child nodes from all elements in the source document.
With this issue sorted out, let's build the post-obit uncomplicated XSQL page to test EmpUsingRowStar.xsl on live database data:
<?xml version="1.0"?><!-- Emp.xsql --><xsql:query connection="xmlbook" xmlns:xsql="urn:oracle-xsql">SELECT empno, ename, sal, deptnoFROM empORDER BY ename DESC</xsql:query>
The query in this page includes a couple of actress columns and, instead of just returning the rows for `KING' and `SCOTT', will render all the rows in the emp table. As nosotros saw in Chapter iii, Combining XML and Oracle, nosotros can reuse the information from the Emp.xsql page past including information technology in other XSQL pages with the <xsql:include-xsql> action. In this way, we can employ different stylesheets to the same information page produced. This will come in handy to test the diverse stylesheets nosotros develop in the rest of this affiliate.
For example, we tin can create an EmpUsingRowStar.xsql page that includes Emp.xsql and associates the EmpUsingRowStar.xsl stylesheet to information technology. The page looks like this:
<?xml version="i.0"?><!-- EmpUsingRowStar.xsql --><?xml-stylesheet type="text/xsl" href="EmpUsingRowStar.xsl"?><!-- Include Emp.xsql and manner it with EmpUsingRowStar.xsl --><xsql:include-xsql href="Emp.xsql" xmlns:xsql="urn:oracle-xsql"/>
Running EmpUsingRowStar.xsql from JDeveloper 3.1 we tin can see the results shown in Figure 7-eight.
| |
And then our ROW/* template is correctly working not only for the <EMPNO> and <ENAME> elements, just too for the boosted <SAL> and <DEPTNO> elements in the result. However, the results look pretty manifestly and are missing column headers. Permit's fix that.
Processing Source Nodes in Different Modes
Today, many developers creating HTML pages use Cascading Style Sheets (CSS) to separate the presentation style information for many pages into a unmarried, external stylesheet file, so reference the CSS stylesheet from the HTML pages to control font and colour information globally. We can leverage this same tried and true technique in the HTML pages we create just by placing the correct <link> tag inside the <head> section of our HTML page. If our CSS stylesheet is called Table.css then the <caput> and <link> elements we need look like this:
<head><link rel="stylesheet" type="text/css" href="Tabular array.css"/></caput> To create table column headers in a generic way, we need to process all child elements of a <ROW> so use the names of the elements--equally opposed to their values--as the content of the table header cells. All the same, we already have a template with a ROW/* match pattern to procedure the children of a <ROW>; we're using information technology to create the table cells for each row generically.Specifically, we need a way to procedure the same source tree elements multiple unlike ways to generate the cavalcade headers. We need to process the children of a <ROW> as follows:
- Once in a special "Cavalcade Headers" mode, to transform the children of a
<ROW>into the advisable column headers - Once in a regular mode to format the query results
Luckily, XSLT has just the functionality nosotros need. When you create a template, in addition to the match design, it can also accept a way attribute that assigns a name to the special mode in which you want to invoke the template. Since we need a special way to format column headers, nosotros tin create a template with match="ROW/*" and fashion="ColumnHeaders". The name of the mode needs to be meaningful only to u.s.; the processor never interprets the name in any style. The template looks like this:
<!-- Match any element child of a ROW when in "ColumnHeaders" Manner --><xsl:template match="ROW/*" style="ColumnHeaders"><thursday><!-- Put the value of the *proper noun* of the electric current chemical element --><xsl:value-of select="proper noun(.)"/></th></xsl:template>
Now, when nosotros're processing a <ROW> chemical element child in ColumnHeaders mode, we create <th> tabular array header elements instead of <td> table jail cell elements, and nosotros use the XPath name( ) office to refer to the name of the current chemical element instead of to its value. Remember that in XPath, the dot represents the current node, so name (.) is the name of the current node.
When you create templates with an associated mode, you have to explicitly request that the engine process a listing of nodes using that mode. You accomplish this by going across the default utilize of <xsl:use-templates> (which, past default, processes the children of the current node without using whatsoever special mode) to include a way="CurrentHeaders" attribute, like this:
<!-- Apply templates to children of the current node in "ColumnHeader" mode --><xsl:apply-templates style="ColumnHeaders"/>
Nosotros demand the cavalcade headers to exist created before all of the <ROW> elements are candy to produce the tabular array rows, and then we add the above <xsl:apply-templates> inside our ROWSET template, like this:
<xsl:template match="ROWSET"><table border="1" cellspacing="0"><!-- Apply templates in "ColumnHeader" mode first --><xsl:use-templates style="ColumnHeaders"/><!-- Then apply templates to all child nodes normally --><xsl:use-templates/></table></xsl:template>
However, if nosotros attempt to apply this template as is, the <xsl:use-templates> for the ColumnHeader mode will process all of the child nodes of the <ROWSET>, since that's what <xsl:apply-templates> does. This will produce a prepare of cavalcade headers beyond the top for each <ROW> in the <ROWSET>, which will give u.s.a. many repeated cavalcade headers. We demand to process only a single child <ROW> of the <ROWSET> to option upwards the column header names.
Nosotros can handle this easily by modifying the default beliefs of <xsl:apply-templates> by adding an optional select attribute that specifies an XPath expression, identifying the list of nodes to process. We accomplish this past changing:
<xsl:employ-templates manner="ColumnHeaders"/> to:
<xsl:apply-templates select="ROW[1]/*" mode="ColumnHeaders"/> At present we can select the list of child elements under only the outset <ROW> child of <ROWSET>. This will give us just a single set of column headers.
There is no longer anything specific to the Emp.xml certificate left in this stylesheet. Information technology tin handle the task of transforming any <ROWSET> into an HTML table with cavalcade headers, then we'll name it accordingly. The final TableBaseWithCSS.xsl stylesheet, incorporating CSS and column headers, produced using modes, appears in Example 7-5.
Example 7-5: Transforming Whatever ROWSET into a Table with Headers
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><!--| TableBaseWithCSS:| Bones stylesheet to format any ROWSET of ROWS into a tabular array| with cavalcade headings in a generic style. Leverages Table.css| CSS stylesheet to control font/color information for the page.+--><xsl:template match="/"><html><!-- Generated HTML outcome will be linked to Table.css CSS stylesheet --><head><link rel="stylesheet" blazon="text/css" href="Table.css"/></head><torso><xsl:use-templates/></trunk></html></xsl:template><xsl:template match="ROWSET"><tabular array border="one" cellspacing="0"><!-- Apply templates in "ColumnHeader" fashion to just *offset* ROW child --><xsl:utilise-templates select="ROW[1]/*" mode="ColumnHeaders"/><!-- Then apply templates to all child nodes normally --><xsl:apply-templates/></table></xsl:template><xsl:template match="ROW"><tr><xsl:apply-templates/></tr></xsl:template><!-- Match any element child of a ROW --><xsl:template match="ROW/*"><td><xsl:apply-templates/></td></xsl:template><!-- Match whatsoever element child of a ROW when in "ColumnHeaders" Manner--><xsl:template friction match="ROW/*" fashion="ColumnHeaders"><th><!-- Put the value of the *name* of the electric current element --><xsl:value-of select="name(.)"/></th></xsl:template></xsl:stylesheet>
If nosotros create an XSQL page to examination the stylesheet in a higher place, we see that the result looks like Figure 7-9.
| |
We've seen that past using multiple templates, it's possible to build stylesheets that procedure source nodes in a more than generic way, and that we can use modes to process the same source tree nodes in different ways. Next, nosotros'll start to see how templates can be overridden to build on base libraries of existing templates to create custom templates for new tasks.
Reusing and Customizing Existing Stylesheets
Let'due south say we need to produce a table displaying employee information where employees who earn more than than $2000 are highlighted. This task differs from our previous piece of work in only one small particular: ROWs with a SAL > 2000 need to be highlighted differently from other ROWs. We hope it's possible to focus just on this new requirement. It nigh definitely is possible with XSLT.
Nosotros tin create a new EmpOver2000.xsl stylesheet that builds on our TableBaseWithCSS.xsl stylesheet and adds one new template to handle the new highlighting chore. We can leverage our previous work by using the <xsl:import> action at the top level of our stylesheet to import all of the templates nosotros've already created for doing the bones job of formatting a <ROWSET> as a tabular array. Example 7-6 shows the minimal syntax we demand.
Example 7-6: Importing a Base Stylesheet and Calculation New Templates
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><!-- Import all the templates from "TableBaseWithCSS.xsl" as a base --><xsl:import href="TableBaseWithCSS.xsl"/><!-- Override imported template for ROW to match ROWs with a SAL > 2000 --><xsl:template match="ROW[ SAL > 2000 ]"><tr course="Highlight"><xsl:apply-templates/></tr></xsl:template></xsl:stylesheet>
Nosotros've imported the TableBaseWithCSS.xsl stylesheet and added a template with the match blueprint of ROW[SAL>2000] to match nodes with a <SAL> kid chemical element whose value is greater than 2000. Rather than hard-coding font and colour information directly into the template, detect that we're using a CSS class aspect to refer to the name of a CSS class called Highlight that will externally specify the fonts and colors to use for highlighted rows. If we raise our previous Table.css to include the new Highlight CSS course like this:
body { font-family: Verdana }thursday { background-color: xanthous }.Highlight { background-colour: #e7e7e7 }
then all that'due south left to practice is to build an XSQL page to include our original Emp.xsql data and transform it using EmpOver2000.xsl like this:
<?xml version="1.0"?><?xml-stylesheet type="text/xsl" href="EmpOver2000.xsl"?><xsql:include-xsql href="Emp.xsql" xmlns:xsql="urn:oracle-xsql"/>
Now, when we request this new EmpOver2000.xsql page, we see what's shown in Figure 7-10.
| |
When processing the source tree using this stylesheet, for each child <ROW> in the list of children of the <ROWSET> element, the XSLT processor looks for templates that match <ROW>. Before, at that place was only a unmarried template with a match pattern of "ROW", and then in that location was merely 1 template to choose from. However, in EmpOver2000.xsl the lucifer="ROW" template is imported from the TableBaseWithCSS.xsl stylesheet, and we've likewise added a new match="ROW[SAL>2000]" template. This ways that when processing a <ROW> element in the electric current node list for rows that have a <SAL> over 2000, the processor finds 2 matching templates. Since the electric current node is a <ROW> element, information technology matches the lucifer="ROW" template, simply since it's a <ROW> with a SAL greater than 2000, it as well matches the match="ROW[SAL>2000]" template.
Call up from the basic transformation rules we learned before in this affiliate that the processor considers all matching templates and then selects the ane that matches best. In this example, the ROW[SAL>2000] is a more specific blueprint than the basic ROW pattern, then ROW[SAL>2000] qualifies as a better lucifer.
Let's endeavor another example that imports TableBaseWithCSS.xsl and:
- Formats even-numbered rows in ane color
- Formats odd-numbered rows in a different color
- Formats rows in the "Meridian-Secret" department to say "Classified"
The stylesheet that accomplishes these tasks appears in Case 7-seven.
Instance vii-7: Formatting Alternate Rows and Conditionally Hiding Data
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"><!-- Import all the templates from "TableBaseWithCSS.xsl" every bit a base --><xsl:import href="TableBaseWithCSS.xsl"/><!-- Match all ROWS in Pinnacle-Hush-hush Department xx --><xsl:template match="ROW[ DEPTNO = 20 ]"><tr><td align="center" colspan="{count(*)}"><tabular array edge="0"><tr><td>Classified</td></tr></table></td></tr></xsl:template><!-- Match all fifty-fifty ROWS --><xsl:template lucifer="ROW[ position( ) mod two = 0 ]"><tr class="Fifty-fifty"><xsl:apply-templates/></tr></xsl:template><!-- Lucifer all odd ROWS --><xsl:template friction match="ROW[ position( ) modernistic 2 = i ]"><tr form="Odd"><xsl:utilise-templates/></tr></xsl:template></xsl:stylesheet>
The stylesheet contains three boosted templates that match:
- Fifty-fifty rows with
ROW[position( ) mod 2 = 0] - Odd rows with
ROW[position( ) mod two = ane] - Top-Secret rows with
ROW[DEPTNO=20]
The stylesheet leverages the XPath position( ) function and mod operator to calculate the remainder by integer division by two of the electric current position in the current node list. Rows in fifty-fifty-numbered positions will exist divisible by 2 then they have a zero remainder. Rows in odd-numbered positions accept a rest of 1.
Applying this stylesheet produces the results shown in Effigy 7-eleven. This does format the even and odd rows but--oops!--we've just revealed our Meridian-Cloak-and-dagger Department 20 information to users browsing the page.
| |
This unexpected result occurs because of the way XSLT resolves conflicts among multiple matching XPath expressions. For rows in Section 20, the XSLT processor considers all the templates that match the <ROW> chemical element in question. If the row is in an even position in the listing, it will match both ROW[position( ) mod ii = 0] and ROW[DEPTNO=xx]. Similarly, if information technology's in an odd position in the list, it will lucifer the ROW[position( ) mod ii =0] template and the ROW[DEPTNO=xx] template. Dissimilar the previous example nosotros worked with (when it was clear to the processor that one template was more specific than another), in this case, both templates match a specific <ROW> element name and both templates take a qualifying predicate. Based on the XSLT template conflict resolution rules, neither i is better. In this state of affairs, the processor picks the template that occurs terminal in the stylesheet. ROW[DEPTNO=20] was never selected considering it was at the top of the stylesheet, higher up both the "even row" and "odd row" templates.
Fugitive Template Conflicts with Priorities
The bones scheme for determining which templates are more than specific than others is as follows: the generic pattern * is less specific than a design similar SOMETHING or xyz:SOMETHING, which is less specific than SOMETHING[predicate] or SOMETHING / SOMETHINGELSE.
But when multiple patterns be at the same level of specificity, you have to help the XSLT processor by telling information technology explicitly which templates are higher priority than others. You lot tin can assist the processor in this tie-breaking task by assigning a priority=" realnumber " aspect on your template. The priority tin can be any positive or negative real number. When no "best" template can exist selected automatically past the processor, the template with the highest assigned priority wins. A priority greater than 0.5 makes your template more of import than whatever of the built-in priorities.
So, if we add a priority="ii" attribute to our ROW[DEPTNO=xx] template, nosotros make information technology more than important than the even row and odd row templates. When a row with DEPTNO equal to 20 is processed, the ROW[DEPTNO=twenty] template volition be chosen by the processor. Case 7-8 shows the stylesheet with the priority properly indicated.
Example seven-8: Getting the Correct Template to Fire by Indicating Priorities
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="one.0"><!-- Import all the templates from "TableBaseWithCSS.xsl" as a base --><xsl:import href="TableBaseWithCSS.xsl"/><!-- Match all ROWS in Top-Secret Department xx --><xsl:template match="ROW[ DEPTNO = 20 ]" priority="2"><tr><td align="center" colspan="{count(*)}"><table border="0"><tr><td>Classified</td></tr></table></td></tr></xsl:template><!-- Match all even ROWS --><xsl:template lucifer="ROW[ position( ) modernistic 2 = 0 ]"><tr form="Even"><xsl:apply-templates/></tr></xsl:template><!-- Friction match all odd ROWS --><xsl:template match="ROW[ position( ) mod 2 = 1 ]"><tr form="Odd"><xsl:apply-templates/></tr></xsl:template></xsl:stylesheet>
Rerunning the case with this modified stylesheet shows us that the event is now what we are expecting, as illustrated in Figure vii-12.
| |
Creating Reusable Named Templates
Next, we'll await at a simple instance of formatting numbers to make salaries announced as dollars and cents and we'll refine our strategy for coloring the alternating rows. XSLT includes the format-number( ) function, which allows any element whose value can exist converted to a number to exist formatted using the number format masks specified past the java.text.DecimalFormat class in the Coffee JDK. Nosotros run into this function in action in the following stylesheet:
<xsl:stylesheet version="one.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><!-- Import all the templates from "TableBaseWithCSS.xsl" as a base --><xsl:import href="TableBaseWithCSS.xsl"/><!-- Some other technique for alternating row colors --><xsl:template match="ROW"><!-- value of class attribute will alternate betwixt "tr0" and "tr1" --><tr class="tr{position( ) mod 2}"><xsl:employ-templates/></tr></xsl:template><xsl:template match="ROW/SAL"><td align="right"><xsl:value-of select="format-number(.,'$0.00')"/></td></xsl:template></xsl:stylesheet>
Hither we're again importing the TableBaseWithCSS.xsl and including a template to attain alternating row coloring, too as a template matching ROW/SAL to override the formatting of <SAL> elements that occur equally children of <ROW> elements. Note that we're employing a different technique to handle the alternate rows in this case. Rather than using separate even row and odd row templates, nosotros use a unmarried <ROW> template simply alternate the name of the CSS class in use on the row by using an aspect value template:
<tr class="tr{position( ) mod two}"><xsl:apply-templates/></tr> This constructs <tr> elements in the result that will have a grade aspect whose value will alternate between tr0 and tr1, depending on whether we're in an even or odd row, respectively. Nosotros tin add CSS classes in our Table.css CSS stylesheet to define the colors we desire, like this:
body { font-family: Verdana; font-size: 8pt }th { background-color: yellowish }.Highlight { background-color: #e7e7e7 }.tr1 {background-color: #f7f7e7; colour: black}.tr0 {groundwork-color: #f9f9f9; color: black}
Past building a quickie XSQL folio to include Emp.xsql and format information technology with this new stylesheet, as follows:
<?xml version="1.0"?><?xml-stylesheet blazon="text/xsl" href="FormatSal.xsl"?><xsql:include-xsql href="Emp.xsql" xmlns:xsql="urn:oracle-xsql"/>
nosotros can request the page and see the results shown in Figure 7-xiii.
| |
If we conceptualize frequently needing to format table cells with numeric values, we can further factor our templates for reuse past creating a named template to handle the formatting. We can replace the friction match attribute on the <xsl:template> chemical element with a name aspect to plough the template into a callable subroutine to be used in whatsoever situation requiring a tabular array cell to be formatted as dollars and cents, like this:
<!-- "Utility" template to format money is a common fashion --><xsl:template proper noun="moneyCell"><td align="correct"><xsl:value-of select="format-number(.,'$0.00')"/></td></xsl:template>
And then, wherever we need to invoke the template, nosotros can use <xsl:call-template> to invoke the subroutine by proper name with the syntax:
<xsl:phone call-template proper name="moneyCell"/> Named templates are never automatically triggered by the processor; they must be explicitly invoked. When a calling template invokes a named template using <xsl:call-template>, the literal elements and xsl actions in the named template are instantiated as if they had been included at the current position in the invoking template. This means that the chosen template sees the same electric current node as the template that invoked it, in contrast to <xsl:apply-templates select=" design "/ >, which changes the electric current node list.
when you mean: <!-- My template to match ROWSET/ROW --> <xsl:template match="ROWSET/ROW">Another related mistake is to accidentally type: <!-- Utilise templates matching ROWSET/ROW incorrectly--> <xsl:apply-templates match="ROWSET/ROW">
Like other templates, named templates can be included in a "library" stylesheet that is destined to be imported when their functionality is needed; for case:
<xsl:stylesheet version="one.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><!-- Handle fifty-fifty/odd formatting of rows using CSS classes "tr0" and "tr1" --><xsl:template match="ROW"><tr class="tr{position( ) modernistic two}"><xsl:apply-templates/></tr></xsl:template><!-- "Utility" template to format money is a mutual manner --><xsl:template name="moneyCell"><td align="right"><xsl:value-of select="format-number(.,'$0.00')"/></td></xsl:template></xsl:stylesheet>
We tin can include both our alternating row coloring and our named moneyCell template in this CommonLibrary.xsl stylesheet so import it into the post-obit FormatSalUsingLibrary.xsl stylesheet:
<xsl:stylesheet version="one.0" xmlns:xsl="http://world wide web.w3.org/1999/XSL/Transform"><xsl:import href="TableBaseWithCSS.xsl"/><xsl:import href="CommonLibrary.xsl"/><xsl:template match="ROW/SAL"><xsl:telephone call-template name="moneyCell"/></xsl:template></xsl:stylesheet>
Observe that the ROW/SAL template here uses an <xsl:telephone call-template> to invoke the mutual moneyCell template's services by proper name. The event is the same as that produced by our before stylesheet, but now we're reusing common templates from 2 dissimilar libraries, including both normal blueprint-matching templates and named templates.
At this point, we've got our XSLT feet firmly planted on the ground and we're ready to delve deeper into using XSLT in combination with Oracle XSQL Pages in the side by side chapter. And then in Chapter nine, XSLT Beyond the Basics, we encompass a number of of import XSLT topics beyond the basics we've learned here, including using XSLT variables, efficient sorting and grouping of information, and a number of basic transformation techniques for XML datagrams. We'll see in the many examples throughout the rest of this volume that by using XSQL Pages together with stylesheets, we can publish whatsoever information in whatever format nosotros need for the Spider web.
lopezhatintibleat.blogspot.com
Source: http://www1.isti.cnr.it/~Martinelli/XML/doc/xsl/templates.html
0 Response to "Xslt Can We Use Same Value Again"
Post a Comment