tags:

views:

72

answers:

1

Hello,

I try to change my XML-File via XSLT. The file is like:

<A1>
<A2>
<A3>
<b>a</b>
<b>b</b>
...
</A3>
</A2>
</A1>
<A1>
<A2>
<A3>
<b>1</b>
<c>2</c>
</A3>
</A2>
</A1>
...

The result should be:

<A1>
<A2>
<A3>
<b>a, b</b>
</A3>
</A2>
</A1>
<A1>
<A2>
<A3>
<b>1</b>
<c>2</c>
</A3>
</A2>
</A1>

Could anybody help me with that?!!!! Regards

A: 

It depends greatly on a number of things that you haven't mentioned, like are the children elements always in order (i.e. will it always be <b><b><c> or might it be <b><c><b>) and are the elements always the children of the <A3> element.

For the above XML I've written a template to process the element as follows:

<xsl:template match="A3">
    <A3>
    <xsl:for-each select="*">
            <xsl:choose>
                    <xsl:when test="following-sibling::*[name()=current()/name()] and not(preceding-sibling::*[name()=current()/name()])">
                        <xsl:element name="{name()}">
                        <xsl:for-each select="self::* | following-sibling::*[name()=current()/name()]">
                                <xsl:value-of select="."/>
                                <xsl:if test="position() != last()">,</xsl:if>
                            </xsl:for-each>
                            </xsl:element>
                        </xsl:when>
                    <xsl:when test="not(following-sibling::*[name()=current()/name()]) and preceding-sibling::*[name()=current()/name()]">
                        </xsl:when>
                        <xsl:otherwise>
                            <xsl:copy-of select="."/>
                            </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each>
        </A3>
</xsl:template>

There is probably an easier way of doing this but this is one way at least. It might be slow depending on the number of children elements you have for a particular node.

samjudson