I'm a complete XSLT new beginner but I need to use it for a project I'm working on.
I have an XML file thant looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<table>
<CLASS>
<Name></Name>
<Sex></Sex>
<Age></Age>
<Height></Height>
<Weight></Weight>
</CLASS>
</table>
and my desired output should look like this
<table>
<CLASS>
<Name>
<Sex>
<Age>
<Height>
<Weight>
</Weight>
</Height>
</Age>
</Sex>
</Name>
</CLASS>
</table>
I have now spent 2 days but I'm not able to fine a solution for that. I tried using for-each and read about grouping but unsure how to perform such change in nesting structure. I'm using XSLT 1.
CodePudding user response:
This doesn't look as a task suitable for "a complete XSLT noob".
Assuming that each element under CLASS
is supposed to be nested inside its immediately preceding sibling, you could adapt a method known as "sibling recursion":
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/table">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="CLASS">
<xsl:copy>
<xsl:apply-templates select="*[1]"/>
</xsl:copy>
</xsl:template>
<xsl:template match="CLASS/*">
<xsl:copy>
<xsl:apply-templates select="following-sibling::*[1]"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>