XSLT Basic
XSLT全称eXtended Stylesheet Language Transformation
xslt文件头:
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"> <xsl:output method="xml" indent="yes"/>
重要标签解析:
<xsl:template match="xpath"> 该标签用于定义模版,同时分配给指定结点
<xsl:apply-templates select="xpath"> 该标签用于指定要应用模版的结点
提示: xsl:template中可以再次使用xsl:apply-templates,用于样式的多级嵌套
实例1:
planets.xml
<?xml version="1.0" encoding="utf-8"?> <?xml-stylesheet type="text/xsl" href="planets.xslt"?> <planets> <planet color="red"> <name>Mercury</name> <mass units="(Earth=1)">.0553</mass> <day units="days">58.65</day> <radius units="miles">1516</radius> <density units="(Earth=1)">.983</density> <distance units="million miles">43.4</distance> </planet> <planet color="yellow"> <name>Venus</name> <mass units="(Earth=1)">.815</mass> <day units="days">116.75</day> <radius units="miles">3716</radius> <density units="(Earth=1)">.943</density> <distance units="million miles">66.8</distance> </planet> </planets>
planet.xslt
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"> <xsl:output method="html" indent="yes"/> <xsl:template match="/"> <html> <body> <xsl:apply-templates/> </body> </html> </xsl:template> <xsl:template match="planet"> <p> <xsl:value-of select="name"/> </p> </xsl:template> </xsl:stylesheet>
以上例子中,先对所有结点使用<xsl:apply-templates>,然后再使用<xsl:template>对planet结点作处理
<xsl:value-of select="xpath"> 获得结点的值
语法结构的使用
-
类似于if(){...}else{}的语法
<xsl:if test="expression/condition"> </xsl:if>
-
类似于switch(){case n: ...}的语法
<xsl:choose> <xsl:when test="condition"></xsl:when> <xsl:when test="condition"></xsl:when> <xsl:otherwise></xsl:otherwise> </xsl:choose>
-
foreach语法
<xsl:for-each select="node1"> </xsl:for-each>
-
模版函数定义
<xsl:template name="template1"> <xsl:param name="parameter1"/> <xsl:param name="parameter2" select="defaultvalue"/> </xsl:template>
其中,parameter2使用select属性指定了默认值defaultvalue。
对于模版函数中的参数可以用$variable来引用
实例3:
<xsl:call-template name="template1"> <xsl:with-param name="parameter1"/> </xsl:call-template>