Developer42

2010-06-29

Grouping Items using XSLT

Filed under: Technology — Tags: , , , , , , — Developer42 @ 12:16

Another XSLT problem. How do you group items together using XSLT, when the sort function isn’t available (e.g. the Muenchian Method won’t work).

The XSLT

<xsl:stylesheet version="2.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  
  <xsl:output method="xml" indent="yes" encoding="utf-8" /> <!-- keeping utf 8 rather than 16 as this will be big -->
  <xsl:strip-space elements="*"/>

  <!-- ROOT -->
  <xsl:template match="/node()">
    <xsl:copy>
      <xsl:copy-of select="@*"/>
      <xsl:for-each select="./node()[not(journalName = preceding-sibling::Row/journalName)]/node()[local-name()=&quot;journalName&quot;]"><!-- for each distinct JournalName -->
        <xsl:variable name="journalName"><xsl:value-of select="."/></xsl:variable>
        <Journal>
          <xsl:copy-of select="."/>
          <xsl:apply-templates select="//node()[local-name()=&quot;Row&quot; and journalName=$journalName]" />
        </Journal>
      </xsl:for-each>
    </xsl:copy>
  </xsl:template>

  <!-- By default, copy everything as is -->
  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>
  
  <!-- but as we already have the journal name, strip it -->
  <xsl:template match="node()[local-name()=&quot;journalName&quot;]" />
  
  <!-- and demo that we could manipulate other elements if needed -->
  <xsl:template match="node()[local-name()=&quot;otherData&quot;]">
    <xsl:copy>
      <xsl:copy-of select="@*" />
      <xsl:attribute name="newAttribute">Demo</xsl:attribute>
      <xsl:value-of select="."/>
    </xsl:copy>
  </xsl:template>
  
</xsl:stylesheet>

Sample Data

<Root>
  <Row>
    <journalName>a</journalName>
	<otherData>hello1</otherData>
	<other>hellox1</other>
  </Row>
  <Row>
    <journalName>a</journalName>
	<otherData>hello2</otherData>
	<other>hellox2</other>
  </Row>
  <Row>
    <journalName>b</journalName>
	<otherData>hello3</otherData>
	<other>hellox3</other>
  </Row>
  <Row>
    <journalName>b</journalName>
	<otherData>hello4</otherData>
	<other>hellox4</other>
  </Row>
  <Row>
    <journalName>a</journalName>
	<otherData>hello5</otherData>
	<other>hellox5</other>
  </Row>
</Root>
Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: