XSLT 1.0如何获得不同的值

问题描述:

我有一个与下面所示类似的XML。我必须找到独特的类别。 XSLT 2.0中有许多简单的方法。但我必须坚持1.0 :(。经过几番努力后,我找到了解决方案。我想分享。可以帮助别人。请改善我的答案。谢谢。

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>

解决方案。我已经在答案部分中添加了。

解决方案

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

输出

Games,Books,Food,Travel

源代码

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