XSLT grouping every 4 adjacent elements -
i have xml below.
source xml:
<?xml version="1.0" encoding="windows-1252"?> <xml> <attributes> <attribute> <name>collection</name> <value /> </attribute> <attribute> <name>a</name> <value>testing</value> </attribute> <attribute> <name>b</name> <value>blank</value> </attribute> <attribute> <name>c</name> <value>11</value> </attribute> <attribute> <name>d</name> <value>na</value> </attribute> <attribute> <name>a</name> <value>testing1</value> </attribute> <attribute> <name>b</name> <value>red</value> </attribute> <attribute> <name>c</name> <value>12</value> </attribute> <attribute> <name>d</name> <value>nat</value> </attribute> </attributes> </xml> from above xml how can this. want group them in groups of 4. first 4 (in source xml) element /attribute/name='a' - /attribute/name='d' in first group. , next 4 /attribute/name='a' - /attribute/name='d' in second group .... below
thanks in advance
output
<collection name="collection" > <complexattr> <attr name="a" value="testing" /> <attr name="b" value="blank" /> <attr name="c" value="11" /> <attr name="d" value="na" /> </complexattr> <complexattr > <attr name="a" value="testing1" /> <attr name="b" value="red" /> <attr name="c" value="12" /> <attr name="d" value="na" /> </complexattr> </collection>
this faq. see link in comments question. here stylesheet tailored input , desired output:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <!-- number of items include in each group --> <xsl:variable name="group" select="4" /> <xsl:template match="/"> <collection name="collection"> <xsl:apply-templates select="xml/attributes/attribute[not(name='collection')] [position() mod $group = 1]" /> </collection> </xsl:template> <xsl:template match="attribute" mode="inner"> <attr name="{name}" value="{value}" /> </xsl:template> <xsl:template match="attribute"> <complexattr> <xsl:apply-templates select=".|following-sibling::attribute[position() < $group]" mode="inner" /> </complexattr> </xsl:template> </xsl:stylesheet> produces:
<collection name="collection"> <complexattr> <attr name="a" value="testing" /> <attr name="b" value="blank" /> <attr name="c" value="11" /> <attr name="d" value="na" /> </complexattr> <complexattr> <attr name="a" value="testing1" /> <attr name="b" value="red" /> <attr name="c" value="12" /> <attr name="d" value="nat" /> </complexattr> </collection>
Comments
Post a Comment