代码之家  ›  专栏  ›  技术社区  ›  majkinetor

用于检查变量是否属于元素集的XSLT表达式

  •  16
  • majkinetor  · 技术社区  · 17 年前

      <xsl:if test="$k='7' or $k = '8' or $k = '9'">
    

    有没有办法把这个表达式放到一个表单中,比如SQL

       k IN (7, 8, 9)
    

    泰:)

    2 回复  |  直到 17 年前
        1
  •  28
  •   Tomalak    17 年前

    XSLT/XPath 1.0:

    <!-- a space-separated list of valid values -->
    <xsl:variable name="list" select="'7 8 9'" />
    
    <xsl:if test="
      contains( 
        concat(' ', $list, ' '),
        concat(' ', $k, ' ')
      )
    ">
      <xsl:value-of select="concat('Item ', $k, ' is in the list.')" />
    </xsl:if>
    

    如果需要,您可以使用其他分离器。

    在XSLT/XPath 2.0中,您可以执行以下操作:

    <xsl:variable name="list" select="fn:tokenize('7 8 9', '\s+')" />
    
    <xsl:if test="fn:index-of($list, $k)">
      <xsl:value-of select="concat('Item ', $k, ' is in the list.')" />
    </xsl:if>
    

    如果可以使用文档结构定义列表,则可以执行以下操作:

    <!-- a node-set defining the list of currently valid items -->
    <xsl:variable name="list" select="/some/items[1]/item" />
    
    <xsl:template match="/">
      <xsl:variable name="k" select="'7'" />
    
      <!-- test if item $k is in the list of valid items -->
      <xsl:if test="count($list[@id = $k])">
        <xsl:value-of select="concat('Item ', $k, ' is in the list.')" />
      </xsl:if>
    </xsl:template>
    
        2
  •  8
  •   CodeManX    7 年前

    如果您的处理器支持XPath2.0,那么您可以比较 $k 按照这样的顺序:

    <xsl:if test="$k = (7, 8, 9)">
    

    在这种特殊情况下,您甚至可以使用范围运算符:

    <xsl:if test="$k = (7 to 9)">
    

    不需要显式类型转换。使用Saxon HE 9.8.0.12N(XSLT 3.0)进行测试。

    XML示例:

    <?xml version="1.0" encoding="UTF-8"?>
    <root>
        <node>5</node>
        <node>6</node>
        <node>7</node>
        <node>9</node>
        <node>10</node>
        <node>79</node>
        <node>8</node>
    </root>
    

    样式表:

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">
    
        <xsl:output method="xml" indent="yes"/>
    
        <xsl:template match="root">
            <xsl:copy>
                <xsl:apply-templates select="node"/>
            </xsl:copy>
        </xsl:template>
    
        <xsl:template match="node">
            <xsl:variable name="k" select="text()"/>
            <xsl:if test="$k = (7 to 9)">
                <xsl:copy-of select="."/>
            </xsl:if>
        </xsl:template>
    
    </xsl:stylesheet>
    

    结果:

    <?xml version="1.0" encoding="UTF-8"?>
    <root>
       <node>7</node>
       <node>9</node>
       <node>8</node>
    </root>