转换文本

XSLT 教程 · 第 6 章 · 7 次浏览

XSLT 用 xsl:variable 定义变量(不可变),配合 XPath 函数做计算。XSLT 1.0 函数有限,2.0/3.0 丰富很多。

变量

<xsl:variable name="tax" select="0.1"/> 定义,$tax 引用。变量值可以是结果树片段或节点集。

常用函数

count()、sum()、string-length()、contains()、substring()、concat()、format-number()(数字格式化)、current()(当前节点)。

代码示例

<xsl:template match="/">
  <html><body>
    <xsl:variable name="total" select="sum(bookstore/book/price)"/>
    <xsl:variable name="count" select="count(bookstore/book)"/>

    <p>共 <xsl:value-of select="$count"/> 本书</p>
    <p>总价:¥<xsl:value-of select="$total"/></p>
    <p>平均价:¥<xsl:value-of select="format-number($total div $count, '#0.00')"/></p>

    <!-- 条件用变量 -->
    <xsl:if test="$total &gt; 100">
      <p><b>总额超过 100,可享优惠</b></p>
    </xsl:if>
  </body></html>
</xsl:template>