XSLT 编程说明概述
XSLT 有许多传统的编程指令。其形式趋于详细,因为它们的语法是基于 XML 元素构建的。
以下部分介绍了在提交、操作、事件和 SNMP 脚本中最常用的 XSLT 编程指令,这些指令在脚本中提供流控制:
<xsl:选择>编程指导
指令<xsl:choose>
是一种条件结构,用于在不同情况下处理不同的指令。它类似于传统编程语言中的 switch 语句。指令<xsl:choose>
包含一个或多个<xsl:when>
元素,每个元素测试一个 XPath 表达式。如果测试的评估结果为 true,则 XSLT 处理器将在元素中<xsl:when>
执行指令。XSLT 处理器在计算结果为 true 的元素中<xsl:when>
找到 XPath 表达式后,XSLT 处理器将忽略指令中包含的<xsl:choose>
所有后续<xsl:when>
元素,即使其 XPath 表达式的计算结果为 true。换句话说,XSLT 处理器仅处理第一个<xsl:when>
元素中包含的指令,其test
属性的计算结果为 true。如果元素的属性均未<xsl:when>
test
为 true,则处理可选<xsl:otherwise>
元素的内容(如果存在 )。
该 <xsl:choose>
指令与其他编程语言中的 switch 语句类似。元素 <xsl:when>
是 switch 语句的“案例”,您可以添加任意数量的 <xsl:when>
元素。该 <xsl:otherwise>
元素是 switch 语句的“default”(默认)。
<xsl:choose> <xsl:when test="xpath-expression"> ... </xsl:when> <xsl:when test="another-xpath-expression"> ... </xsl:when> <xsl:otherwise> ... </xsl:otherwise> </xsl:choose>
<xsl:各>编程指导
该 <xsl:for-each>
元素告诉 XSLT 处理器收集一组节点并逐一处理它们。节点将由属性指定的 select
XPath 表达式选择。然后,根据结构中 <xsl:for-each>
保存的指令处理每个节点。
<xsl:for-each select="xpath-expression"> ... </xsl:for-each>
对于与 XPath 表达式匹配的每个节点,将递归评估指令中的 <xsl:for-each>
代码。也就是说,当前上下文会移动到该语句选择 <xsl:for-each>
的每个节点,而处理则与当前上下文相关。
在以下示例中, <xsl:for-each>
该结构以递归方式处理层次结构中的每个 [system syslog file]
节点。它会为每个匹配节点更新当前上下文,并打印元素的值 name
(如果有)是当前上下文的子元素。
<xsl:for-each select="system/syslog/file"> <xsl:value-of select=”name”/> </xsl:for-each>
<xsl:if> 编程指导
<xsl:if>
编程指令是一种条件结构,如果属性中test
持有的 XPath 表达式的计算结果为true
,则用于处理指令。
<xsl:if test="xpath-expression"> ...executed if test expression evaluates to true </xsl:if>
没有相应的 else 语句。
XSLT 编程指令和伪代码示例
表 1 展示了使用多个 XSLT 编程指令和伪代码解释的示例。
编程指导 |
伪代码解释 |
---|---|
<xsl:choose> <xsl:when test="system/host-name"> <change> <system> <host-name>M320</host-name> </system> </change> </xsl:when> <xsl:otherwise> <xnm:error> <message> Missing [edit system host-name] M320. </message> </xnm:error> </xsl:otherwise> </xsl:choose> |
当语句 否则,发出警告消息: |
<xsl:for-each select="interfaces/ interface[starts-with(name, 'ge-')]/unit"> |
对于在 |
<xsl:for-each select="data[not(value)]/name"> |
选择不包含参数值的任何宏参数。 换句话说,匹配以下形式的所有 apply-macro apply-macro-name { parameter-name; } 请忽略所有 apply-macro apply-macro-name { parameter-name parameter-value; } |
<xsl:if test="not(system/host-name)"> |
|
<xsl:if test="apply-macro[name = 'no-igp'] |
|
<xsl:if test="not(../apply-macro[name = 'no-ldp']) |
|