ksrb
ksrb

Reputation: 1945

Flatten XML using XSLT

Problem

Input:

<root>
    <node attr="nodeAttr">
        <node attr2="childNodeAttr">
            <node attr3="childChildNodeAttr">
                <item>...</item>
                ...
            </node>
        </node>
    </node> 
</root>

Expected Output:

<root>
    <node attr="nodeAttr" attr2="childNodeAttr" attr3="childChildNodeAttr">
        <item>...</item>
        ...
    </node>
</root>

Or

<root>
    <node>
        <attr>nodeAttr</attr>
        <attr2>childNodeAttr</attr2>
        <attr3>childChildNodeAttr</attr3>
        <item>...</item>
        ...
    </node>
</root>

Attempt

<xsl:for-each select="/root/node">
    <xsl:variable name="nodeAttribute" select="@attr" />
    <xsl:for-each select="/root/node/node">
        <xsl:variable name="nodeAttribute2" select="@attr2" />
        <xsl:for-each select="/root/node/node/node">
            <tr>
                <td>
                    <xsl:value-of select="$nodeAttribute"></xsl:value-of>
                </td>
                <td>
                    <xsl:value-of select="$nodeAttribute2"></xsl:value-of>
                </td>
                <td>
                    <xsl:value-of select="@attr3"></xsl:value-of>
                </td>
            </tr>
        </xsl:for-each>
    </xsl:for-each>
</xsl:for-each>

Details

I'm very new to XSLT and having trouble figuring out how to use it. Clearly my attempt above doesn't really make sense.

I've read several examples but I'm having trouble with the more complicated examples. Are there any other good sites besides W3C and w3school that can help me learn?

Thanks!

Upvotes: 0

Views: 1351

Answers (1)

Erlock
Erlock

Reputation: 1968

You can inspire yourself from this sample:

<xsl:template match="root">
  <xsl:copy>
    <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>

<xsl:template match="root/node">
  <xsl:copy>
    <xsl:copy-of select="descendant-or-self::node/@*" />
    <xsl:copy-of select="descendant::item" />
  </xsl:copy>
</xsl:template>

Upvotes: 2

Related Questions