关于xslt:遍历不同的值

Looping over distinct values

给定一个变量,它使用distinct-values()函数返回一个不同的状态列表,是否有办法在for-each循环中标记该变量?

1
2
3
4
5
<States>
<State>AL</State>
<State>AL</State>
<State>NM</State>
</States>

以下变量返回AL和NM,但我无法使用for-each对其进行迭代。有办法解决吗?

1
2
<xsl:variable name="FormStates" select="distinct-values(States/State)"/>
  <xsl:for-each select="$FormStates">

XSLT 2.0正常。


distinct-values()函数返回一个应该迭代的值序列。结果可以说是"令牌化"。

fn:distinct-values('AL', 'AL', 'NL')返回序列('AL', 'NL')

如果使用xsl:value-of输出变量,则仅由于xsl:value-of的默认序列分隔符为单个空格字符,才会返回字符串" AL NL"。您可以使用@separator属性更改此内容:

输入

1
2
3
4
5
6
<?xml version="1.0" encoding="UTF-8"?>
<States>
  <State>AL</State>
  <State>AL</State>
  <State>NM</State>
</States>

XSLT

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
  <xsl:template match="/">
    <xsl:variable name="FormStates" select="distinct-values(States/State)"/>
    <xsl:comment>xsl:value-of</xsl:comment>
    <xsl:value-of select="$FormStates" separator=":"/>
    <xsl:comment>xsl:for-each</xsl:comment>
    <xsl:for-each select="$FormStates">
      <xsl:value-of select="."/>
      <xsl:text>:</xsl:text>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

输出

1
2
3
4
5
<?xml version="1.0" encoding="UTF-8"?>
<!--xsl:value-of-->
AL:NM
<!--xsl:for-each-->
AL:NM:


这是我过去使用的XSLT 1.0解决方案。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  <xsl:template match="/">          
   
<ul>
 
      <xsl:for-each select="//State[not(.=preceding::*)]">
       
<li>

          <xsl:value-of select="."/>
       
</li>
   
      </xsl:for-each>            
   
</ul>

  </xsl:template>

返回:

1
2
3
4
5
6
7
8
9
10
11
12
13
<ul xmlns="http://www.w3.org/1999/xhtml">
 
<li>
AL
</li>

 
<li>
NM
</li>


</ul>

理论上它应该起作用;您确定提供给distinct-values函数的XPath是正确的吗?您提供的代码要求States元素是forms元素的同级元素。

您可以在变量声明之后立即插入<xsl:value-of select="count($FormStates)">,以确认其设置是否正确。