Using xsl:for-each-group in an XSL transformation
Posted by jamie on 20 May 2011 in Activity log
A quick way to select a series of elements in an XSL transformation
for-each-group
, in case something like XPath's distinct-values
function isn't sufficient (for example, when you want to group a series of elements by a certain value but you still want to access all of the other nodes in the elements):
<?xml version="1.0" encoding="UTF-8"?>
<markers xsl:version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:tei="http://www.tei-c.org/ns/1.0">
<xsl:for-each-group select=".//tei:teiHeader" group-by=".//tei:nationality/text()">
<xsl:variable name="nationality" select=".//tei:nationality/text()"/>
<xsl:variable name="geotags" select="normalize-space(.//tei:geo/text())"/>
<xsl:variable name="lat" select="substring-before($geotags, ' ')"/>
<xsl:variable name="lng" select="substring-after($geotags, ' ')"/>
<xsl:element name="marker">
<xsl:attribute name="name" select="$nationality"/>
<xsl:attribute name="address" select="$nationality"/>
<xsl:attribute name="lat" select="$lat"/>
<xsl:attribute name="lng" select="$lng"/>
</xsl:element>
</xsl:for-each-group>
</markers>