An XSL style sheet consists of one or more set of rules that are called templates.
XSLÑùʽ±íÊÇÓÉÒ»¸ö»òÕ߸ü¶àµÄ±»³ÆÎª“Ä£°å£¨templates£©”µÄ¹æÔòÉèÖã¨set of rules£©×é³ÉµÄ¡£
Each template contains rules to apply when a specified node is matched.
µ±ÓëÖ¸¶¨µÄ½ÚµãÆ¥Åäʱ£¬Ã¿¸öÄ£°å¶¼°üº¬ÁËÓ¦ÓùæÔò¡£
The <xsl:template> Element
XSLT<xsl:template>ÔªËØ
The <xsl:template> element is used to build templates.
XSLT<xsl:template>ÔªËØÊÇÓÃÓÚ´´½¨Ä£°åµÄ¡£
The match attribute is used to associate a template with an XML element. The match attribute can also be used to define a template for the entire XML document. The value of the match attribute is an XPath expression (i.e. match="/" defines the whole document).
MatchµÄÊôÐÔµÄ×÷ÓÃÊÇʹģ°åºÍXMLÓëÔªËØÏà½áºÏ¡£MatchÊôÐÔÒ²¿ÉÒÔΪÕû¸öXML¶¨ÒåÄ£°æ¡£MatchÊôÐÔÖµÊÇÒ»¸öXPath±í´ïʽ¡££¨Ò²¾ÍÊÇmatch="/" defines the whole document£©
Ok, let's look at a simplified version of the XSL file from the previous chapter:
ºÃÁË£¬ÏÖÔÚÈÃÎÒÃÇÀ´¿´Ò»ÏÂÕª×ÔÇ°ÃæÕ½ڵÄXSLÎļþµÄ¼òÒ×°æ±¾¡£
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:template match="/"> </xsl:stylesheet> |
Since an XSL style sheet is an XML document itself, it always begins with the XML declaration: <?xml version="1.0" encoding="ISO-8859-1"?>.
ÒòΪXSLÑùʽ±íÊÇXMLÎĵµ±¾Éí£¬ËùÒÔËüÒ»°ã¶¼´ÓXML¿ªÊ¼ÉùÃ÷£º<?xml version="1.0" encoding="ISO-8 59-1"?>¡£
The next element, <xsl:stylesheet>, defines that this document is an XSLT style sheet document (along with the version number and XSLT namespace attributes).
ÏÂÒ»¸öÔªËØ<xsl:stylesheet>£¬°ÑÕâ·ÝÎĵµ¶¨ÒåΪXSLTÑùʽ±íÎĵµ£¨¸ú°æ±¾ºÅºÍXSLTÃüÃû¿Õ¼äÊôÐÔÒ»Ñù£©¡£
The <xsl:template> element defines a template. The match="/" attribute associates the template with the root of the XML source document.
<xsl:template>ÔªËØ¶¨ÒåÁËÒ»·ÝÄ£°å¡£Match=”/”ÊôÐÔʹģ°åºÍXMLÔ´ÎļþµÄ¸ùĿ¼ÁªÏµÆðÀ´¡£
The content inside the <xsl:template> element defines some HTML to write to the output.
<xsl:template>ÔªËØÀïÃæµÄÄÚÈݶ¨ÒåһЩHTMLÀ´¶Ô½á¹û½øÐÐÊéд¡£
The last two lines define the end of the template and the end of the style sheet.
×îºóÁ½Ðж¨ÒåÁËÄ£°æµÄ½áÊø·ûºÍÑùʽ±íµÄ½áÊø·û¡£
The result of the transformation above will look like this:
ͨ¹ýÉÏÃæµÄ´úÂ룬ת»»µÄ½á¹ûÈçÏ£º
My CD Collection
ÎÒµÄCD¼¯
| Title | Artist |
|---|---|
| . | . |
View the XML file, View the XSL file, and View the result
²é¿´XMLÎļþ, ²é¿´ XSLÎļþ, »¹ÓÐ ¿´ÏÂ×îºóµÄ½á¹û
The result from this example was a little disappointing, because no data was copied from the XML document to the output.
ͨ¹ýÕâ¸öÀý×ÓËù²úÉúµÄ½á¹ûÓеãÁîÈËʧÍû£¬ÒòΪûÓн«ÈκÎÊý¾Ý´ÓXMLÎĵµÖи´ÖƵ½½á¹ûµ±ÖС£
In the next chapter you will learn how to use the <xsl:value-of> element to select values from the XML elements.
ÏÂÒ»Õµ±ÖУ¬Ä㽫»áѧϰÈçºÎͨ¹ý<xsl:value-of>ÔªËØ´ÓXMLÔªËØÖÐÑ¡ÔñÖµ¡£