XSLT expression to check if variable belongs to set of elements

后端 未结 2 536
小鲜肉
小鲜肉 2020-12-15 18:16

I have code like this:

  

Is there any way to put this expression in a form, li

相关标签:
2条回答
  • 2020-12-15 18:34

    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>
    

    You can use other separators if needed.

    In XSLT / XPath 2.0 you could do something like:

    <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>
    

    If you can use document structure to define your list, you could do:

    <!-- 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>
    
    0 讨论(0)
  • 2020-12-15 18:54

    If your processor supports XPath 2.0, then you can compare $k to a sequence like so:

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

    You could even use the range-operator in this particular case:

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

    There is no need for an explicit type cast. Tested with Saxon-HE 9.8.0.12N (XSLT 3.0).

    Example 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>
    

    Stylesheet:

    <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>
    

    Result:

    <?xml version="1.0" encoding="UTF-8"?>
    <root>
       <node>7</node>
       <node>9</node>
       <node>8</node>
    </root>
    
    0 讨论(0)
提交回复
热议问题