XSLT 1.0:在方程的右边部分中选择时的多个值?

时间:2012-07-27 09:13:42

标签: xslt xslt-1.0

有没有办法在等式的正确部分放置一个以上的值?

<xsl:choose>
<xsl:when test="Properties/LabeledProperty[Label='Category Code']/Value = 600,605,610">

以上代码返回:

XPath error : Invalid expression
Properties/LabeledProperty[Label='Category Code']/Value = 600,605,610
                                                             ^
compilation error: file adsml2adpay.xsl line 107 element when

我不想使用'OR'的原因是因为每次''''测试时,右边部分应该有大约20个数字。

1 个答案:

答案 0 :(得分:2)

<xsl:stylesheet 
  version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:config="http://tempuri.org/config"
  exclude-result-prefixes="config"
>
  <config:categories>
    <value>600</value>
    <value>605</value>
    <value>610</value>
  </config:categories>

  <xsl:variable 
    name   = "vCategories" 
    select = "document('')/*/config:categories/value" 
  />

  <xsl:key
    name   = "kPropertyByLabel"
    match  = "Properties/LabeledProperty/Value"
    use    = "../Label"
  />

  <xsl:template match="/">
    <xsl:choose>
      <xsl:when test="key('kPropertyByLabel', 'Category Code') = $vCategories">
        <!-- ... -->
      </xsl:when>
    </xsl:choose>
  </xsl:template>

</xsl:stylesheet>

这是有效的,因为在处理节点集时,XPath =运算符会将左侧的每个节点与右侧的每个节点进行比较(与SQL INNER JOIN相当)。

因此,您需要做的就是根据各个值创建一个节点集。使用临时命名空间,您可以在XSLT文件中执行此操作。

另请注意,我引入了<xsl:key>,以便更有效地按标签选择属性值。


编辑:您还可以创建外部config.xml文件并执行此操作:

<xsl:variable name="vConfig" select="document('config.xml')" /> 

<!-- ... -->

<xsl:when test="key('kPropertyByLabel', 'Category Code') = $vConfig/categories/value">

使用XSLT 2.0增加了序列的概念。在那里做同样的事情更简单:

<xsl:when test="key('kPropertyByLabel', 'Category Code') = tokenize('600,605,610', ',')">

这意味着您可以轻松地将字符串'600,605,610'作为外部参数传入。