XSLT 1.0 How to get distinct values

十年热恋 提交于 2020-03-23 14:32:32

问题


I had an XML somewhat similar to what is shown below. I had to find the unique categories. There are lot of easy ways in XSLT 2.0. But I had to stick to 1.0 :( . After several struggle I found the solution. I thought of sharing. Might help somebody. Please improve my answer. I appreciate.

<root>
  <category>
    this is Games category
  </category>
  <category>
    this is Books category
  </category>
  <category>
    this is Food category
  </category>
  <category>
    this is Games category
  </category>
  <category>
    this is Books category
  </category>
  <category>
    this is Food category
  </category>
  <category>
    this is Travel category
  </category>
  <category>
    this is Travel category
  </category>
</root>

Solution. I have added in the answer section. Thanks.


回答1:


Solution

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <xsl:variable name="test">
            <xsl:call-template name="delimitedvalues">
                <xsl:with-param name="paramvalues" select="//category" />
            </xsl:call-template>
        </xsl:variable>

        <xsl:call-template name="distinctvalues">
            <xsl:with-param name="values" select="$test" />
        </xsl:call-template>
    </xsl:template>

    <xsl:template name="distinctvalues">
        <xsl:param name="values"/>
        <xsl:variable name="firstvalue" select="substring-before($values, ',')"/>
        <xsl:variable name="restofvalue" select="substring-after($values, ',')"/>
        <xsl:if test="contains($values, ',') = false">
            <xsl:value-of select="$values"/>
        </xsl:if>
        <xsl:if test="contains($restofvalue, $firstvalue) = false">
            <xsl:value-of select="$firstvalue"/>
          <xsl:text>,</xsl:text>
        </xsl:if>
        <xsl:if test="$restofvalue != ''">
            <xsl:call-template name="distinctvalues">
                <xsl:with-param name="values" select="$restofvalue" />
            </xsl:call-template>
        </xsl:if>
    </xsl:template>

    <xsl:template name="delimitedvalues">
        <xsl:param name="paramvalues" />
        <xsl:value-of select="substring-before(substring-after($paramvalues,'this is '),' category')"/>
        <xsl:if test="$paramvalues/following::category">
            <xsl:text>,</xsl:text>
            <xsl:call-template name="delimitedvalues">
                <xsl:with-param name="paramvalues" select="$paramvalues/following::category" />
            </xsl:call-template>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

Output

Games,Books,Food,Travel

Source Code

http://www.xsltcake.com/slices/0iWpyI


来源:https://stackoverflow.com/questions/17890276/xslt-1-0-how-to-get-distinct-values

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