How to reference grouped elements in XSLT 2.0?

I want to group the following XML file:

<record>
    <word>Hallo</word><translit>XUPPY</translit><gloss>gloss1</gloss>
    <word>Bye</word><translit>EHS</translit><gloss>gloss2</gloss>
    <word>Yes</word><translit>KGR</translit><gloss>gloss3</gloss>
</record>

Desired output is

<s>
    <set><word>Hallo</word><gloss>gloss1</gloss></set>
    <set><word>Bye</word><gloss>gloss2</gloss></set>
    <set><word>Yes</word><gloss>gloss3</gloss></set>
</s>

So I use for-each-group, as in

<xsl:template match="record">
    <xsl:element name="s">
        <xsl:for-each-group select="*" group-starting-with="word">
            <xsl:element name = "set">
                <xsl:copy-of select="current-group()/word"/>
                <xsl:copy-of select="current-group()/gloss"/>
            </xsl:element>
        </xsl:for-each-group>
    </xsl:element>
</xsl:template>

However, I get this output, i.e., empty groups:

<s><set/><set/><set/></s> 

So I am doing something wrong while referencing the elements in the groups. But what? I am sure it must be something simple.

Upvotes: 1

Views: 44

Answers (2)

Martin Honnen
Martin Honnen

Reputation: 167726

The current-group() gives you all the elements in the group, if you want to select a certain element use current-group()[self::gloss].

I would replace

        <xsl:element name = "set">
            <xsl:copy-of select="current-group()/word"/>
            <xsl:copy-of select="current-group()/gloss"/>
        </xsl:element>

with

<set>
  <xsl:copy-of select="., current-group()[self::gloss]"/>
</set>

Upvotes: 3

michael.hor257k
michael.hor257k

Reputation: 117175

word and gloss are members of the current group, not children of it.

Try:

<xsl:template match="/record">
    <s>
        <xsl:for-each-group select="*" group-starting-with="word">
            <set>
                <xsl:copy-of select="current-group()[self::word or self::gloss]"/>
            </set>
        </xsl:for-each-group>
    </s>
</xsl:template>

Upvotes: 3

Related Questions