开发者

XSLT 1.0 Grouping on values of nodes with same name at the same level but different values

开发者 https://www.devze.com 2023-02-19 23:32 出处:网络
I could use some help. Here is an illustrative example of my XML: <items> <item> <name>Thing 1</name>

I could use some help.

Here is an illustrative example of my XML:

<items>
 <item>  
  <name>Thing 1</name>
  <colors>
    <color>white</color>
    <color>green</color>
  </colors>  
  </item>
 <item>  
  <name>Thing 2</name>
  <colors>
    <color>purple</color>
    <color>white</color>
    <color>black</color>  
  </colors>
 </item>
 <item>  
  <name>Thing 3</name>
   <colors/>
 </item>
</items>

A trimmed down example version of my xslt is the following:

<xsl:key name="myGrouping" use="colors/color" match="item"/>  
<xsl:template match="/">
 <xsl:apply-templates select="items" mode="groupingTemplate"/>
</xsl:template>  

<xsl:template mode="groupingTemplate" match="items">  
 <xsl:for-each select="item[cou开发者_如何学编程nt(.|key('myGrouping',colors/color)[1])=1]">  
 <xsl:sort select="colors/color"/>  
 <xsl:if test="count(colors/color)&gt;0">
   <p><xsl:value-of select="colors/color"/></p>
   <xsl:for-each select="key('myGrouping',colors/color)">
   <xsl:sort select="name"/>
    <li><xsl:value-of select="name"/></li>
   </xsl:for-each>
  </xsl:if>
 </xsl:for-each>
</xsl:template>

What I want to do is group in XSLT 1.0 (using the Muenchian method) on the color nodes, so my html output will be:

<p>black</p>  
<li>Thing 2</li>  

<p>green</p>  
<li>Thing 1</li>  

<p>purple</p>  
<li>Thing 2</li>  

<p>white<p>  
<li>Thing 1</li>  
<li>Thing 2</li>  

So far my code can do this but only picks up the first entry. In other words, in the above example my output currently is:

<p>white</p>
<li>Thing 1</li>
<li>Thing 2</li>

Help on a solution and an explanation of why this happens would be greatly appreciated.

Thanks! Jeff


Figured it out after much hair pulling... the following xsl does the trick

<xsl:key name="byColor" use="." match="item/colors/color"/>  
<xsl:template match="/">
  <xsl:apply-templates select="items" mode="groupingTemplate"/>
</xsl:template>  

<xsl:template mode="groupingTemplate" match="items">  
  <xsl:for-each select="item/colors/color[count(.|key('byColor',.)[1])=1]">  
  <xsl:sort select="."/>  
  <xsl:if test="count(.)&gt;0">
    <p><xsl:value-of select="."/></p>
    <xsl:for-each select="key('byColor',.)">
     <xsl:sort select="../../name"/>
        <li><xsl:value-of select="../../name"/></li>
    </xsl:for-each>
   </xsl:if>
   </xsl:for-each>
 </xsl:template>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号