如何使用XSLT创建不同的值

AB.*_*AB. 52 xslt

我有这样的XML:

<items>
  <item>
    <products>
      <product>laptop</product>
      <product>charger</product>
    </products>
  </item>
  <item>
    <products>
      <product>laptop</product>
      <product>headphones</product>  
    </products>  
  </item>
</items>
Run Code Online (Sandbox Code Playgroud)

我希望它输出像

laptop
charger
headphones

我试图使用,distinct-values()但我想我做错了.谁能告诉我如何使用这个distinct-values()?谢谢.

<xsl:template match="/">            
  <xsl:for-each select="//products/product/text()">
    <li>
      <xsl:value-of select="distinct-values(.)"/>
    </li>               
  </xsl:for-each>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

但它给我这样的输出:

<li>laptop</li>
<li>charger</li>
<li>laptop></li>
<li>headphones</li>
Run Code Online (Sandbox Code Playgroud)

Mad*_*sen 51

一个XSLT 1.0解决方案,它使用keygenerate-id()获取不同值的函数:

<?xml version="1.0" encoding="UTF-8"?>
  <xsl:stylesheet
   version="1.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" encoding="UTF-8" indent="yes"/>

<xsl:key name="product" match="/items/item/products/product/text()" use="." />

<xsl:template match="/">

  <xsl:for-each select="/items/item/products/product/text()[generate-id()
                                       = generate-id(key('product',.)[1])]">
    <li>
      <xsl:value-of select="."/>
    </li>
  </xsl:for-each>

</xsl:template>

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)


Nic*_*aly 48

这是我过去使用的XSLT 1.0解决方案,我认为它比使用该generate-id()函数更简洁(和可读).

  <xsl:template match="/">           
    <ul> 
      <xsl:for-each select="//products/product[not(.=preceding::*)]">
        <li>
          <xsl:value-of select="."/>
        </li>   
      </xsl:for-each>            
    </ul>
  </xsl:template>
Run Code Online (Sandbox Code Playgroud)

返回:

<ul xmlns="http://www.w3.org/1999/xhtml">
  <li>laptop</li>
  <li>charger</li>
  <li>headphones</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

  • @NickG我的立场得到了纠正.它确实有效.这是我的xsl处理器设置(eclipse),与我一起做重度多任务处理.还要感谢在线xslt处理器站点链接,不知道它... (3认同)

Tom*_*lak 18

您不需要"输出(distinct-values)",而是"for-each(distinct-values)":

<xsl:template match="/">              
  <xsl:for-each select="distinct-values(/items/item/products/product/text())">
    <li>
      <xsl:value-of select="."/>
    </li>
  </xsl:for-each>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)


小智 14

我在使用Sitecore XSL渲染时遇到了这个问题.使用key()的方法和使用前一轴的方法都执行得非常慢.我最终使用类似于key(​​)的方法,但不需要使用key().它执行得非常快.

<xsl:variable name="prods" select="items/item/products/product" />
<xsl:for-each select="$prods">
  <xsl:if test="generate-id() = generate-id($prods[. = current()][1])">
    <xsl:value-of select="." />
    <br />
  </xsl:if>
</xsl:for-each>
Run Code Online (Sandbox Code Playgroud)


Jim*_*son 9

distinct-values(//product/text())

  • @Nicholas这是针对XSLT 2.0的,但您正在使用XSLT 1.0处理器.你必须使用`<xsl:key>`,就像[接受的答案](http://stackoverflow.com/a/2293626/18771)那样. (2认同)