AmintaCode
AmintaCode

Reputation: 364

Xslt recursive transformation

I've tried in all ways but I got no result. How can I tranform - with XSLT - a XML like this:

<root>
     <row>topic</row>
     <row>Topic1</row>
     <row>words</row>
     <row>word1</row>
     <row>word2</row>
     <row>word3</row>
     <row>words</row>
     <row>word4</row>
     <row>word5</row>
     <row>word6</row>
     <row>topic</row>
     <row>Topic2</row>
     <row>words</row>
     <row>word7</row>
     <row>word8</row>
     <row>word9</row>
     <row>topic</row>
     <row>Topic3</row>
     <row>words</row>
     <row>word10</row>
     <row>word11</row>
     <row>word12</row>
</root>

In a XML like this?

<topic>Topic1
    <words>word1word2word3word4word5word6</words>
</topic>
<topic>Topic2
    <words>word7word8word9</words>
</topic>
<topic>Topic3
    <words>word10word11word12</words>
</topic>

'topic' and 'words' value regularly occur in the XML and I would group first by topic and in each topic group the words by 'words'...

Many thanks in advance!

Upvotes: 0

Views: 76

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116959

In XSLT 2.0, you could so simply:

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

<xsl:template match="root">
    <xsl:copy>
        <xsl:for-each-group select="row" group-starting-with="row[.='topic']">
            <topic>
                <xsl:value-of select="current-group()[2]"/>
                <words>
                    <xsl:value-of select="current-group()[position() gt 3]" separator=""/>
                </words>
            </topic>
        </xsl:for-each-group>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions