Looping over distinct values

混江龙づ霸主 提交于 2019-12-07 03:25:13

问题


Given a variable which returns a list of distinct States using the distinct-values() function, is there a way to tokenize the variable in a for-each loop?

<States>
<State>AL</State>
<State>AL</State>
<State>NM</State>
</States>

The following variable returns AL and NM, but I can't iterate over it using for-each. Is there a way around this?

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

XSLT 2.0 ok.


回答1:


The distinct-values() function returns a sequence of values which you should be able to iterate over. The result is so to speak "tokenized".

fn:distinct-values('AL', 'AL', 'NL') returns the sequence ('AL', 'NL').

If you output the variable with xsl:value-of it will return the string "AL NL" only because the default sequence separator for xsl:value-of is a single space character. This is something you could change with the @separator attribute:

Input

<?xml version="1.0" encoding="UTF-8"?>
<States>
  <State>AL</State>
  <State>AL</State>
  <State>NM</State>
</States>

XSLT

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

Output

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



回答2:


Here's an XSLT 1.0 solution that I've used in the past.

  <xsl:template match="/">           
    <ul> 
      <xsl:for-each select="//State[not(.=preceding::*)]">
        <li>
          <xsl:value-of select="."/>
        </li>   
      </xsl:for-each>            
    </ul>
  </xsl:template>

Returns:

<ul xmlns="http://www.w3.org/1999/xhtml">
  <li>AL</li>
  <li>NM</li>
</ul>



回答3:


In theory it should work; are you sure the XPath given to the distinct-values function is correct? The code you've given requires that the States element is a sibling of the forms element.

You could insert <xsl:value-of select="count($FormStates)"> immediately after the variable declaration to confirm if it is being set properly.



来源:https://stackoverflow.com/questions/3246216/looping-over-distinct-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!