Hi, My issue with xml is, I have an xml like

<a>
    <b>
        <c>
            <d1 att2="t1">test 1</d1>
            <d1>test 2</d1>
            <d1>test 3</d1>
            <d1 att2="t1">test 4</d1>
        </c>
    </b>
</a>

I need to conver this xml to,

<a>
    <b>
        <c>
            <d1 att2="t1">test 1</d1>
            <d1 att2="t1">test 4</d1>
        </c>
    </b>
</a>
<a>
    <b>
        <c>
            <d1>test 2</d1>
        </c>
    </b>
</a>
<a>
    <b>
        <c>
            <d1>test 3</d1>
        </c>
    </b>
</a>

Recommended Answers

All 2 Replies

I thought I had figured it out!

and then I realised they were grouped off att2.

It has been a couple of years since I have used XSLT in anger and can't remember how to do it off the top of my head now :(

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:template match="/">
        <root>
            <xsl:apply-templates select="a"/>
        </root>
    </xsl:template>
    <xsl:template match="a">
        <xsl:apply-templates select="b"/>
    </xsl:template>
    <xsl:template match="b">
        <xsl:apply-templates select="c"/>
    </xsl:template>
    <xsl:template match="c">
        <xsl:apply-templates select="d1[@att2][ position()=1]" mode="a">
            <xsl:with-param name="kn" select="d1[@att2]"/>
        </xsl:apply-templates>
        <xsl:apply-templates select="d1[not(@att2)]"/>
    </xsl:template>
    <xsl:template match="d1">
        <a>
            <b>
                <c>
                    <d1>
                        <xsl:value-of select="."/>
                    </d1>
                </c>
            </b>
        </a>
    </xsl:template>
    <xsl:template match="d1" mode="a">
        <xsl:param name="kn"/>
        <a>
            <b>
                <c>
                    <xsl:for-each select="$kn">
                        <d1>
                            <xsl:value-of select="."/>
                        </d1>
                    </xsl:for-each>
                </c>
            </b>
        </a>
    </xsl:template>
</xsl:stylesheet>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.