How can I use my XSLT file to reorder my XML file in this specific way?
Posted: Fri Oct 28, 2022 12:43 pm
I am trying to transform the following XML file:
The following XSLT file is what I have been using to transform the above file:
The output is:
However, the output I want is as follows:
I seem to be unable to produce this, or how to edit my XSLT file to create this result. Any help would be greatly appreciated!
Code: Select all
<dataroot>
<Student>
<HUSID>idno</HUSID>
<SURNAME>Second Name</SURNAME>
<NUMHUS>idno2</NUMHUS>
<COURSEID>course1</COURSEID>
</Student>
<Student>
<HUSID>idno</HUSID>
<SURNAME>Surname</SURNAME>
<NUMHUS>idno2</NUMHUS>
<COURSEID>course2</COURSEID>
</Student>
<Student>
<HUSID>idno</HUSID>
<SURNAME>Surname</SURNAME>
<NUMHUS>idno2</NUMHUS>
<COURSEID>course3</COURSEID>
</Student>
</dataroot>
Code: Select all
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:template match="dataroot">
<dataroot>
<xsl:apply-templates select="Student[not(HUSID = preceding-sibling::Student/HUSID)]" mode="student"/>
</dataroot>
</xsl:template>
<xsl:template match="Student" mode="student">
<xsl:variable name="husid" select="HUSID"/>
<xsl:variable name="ownstu" select="OWNSTU"/>
<xsl:variable name="birthdte" select="BIRTHDTE"/>
<xsl:variable name="fnames" select="FNAMES"/>
<xsl:variable name="surname" select="SURNAME"/>
<xsl:variable name="ucasperid" select="UCASPERID"/>
<xsl:variable name="uln" select="ULN"/>
<xsl:variable name="numhus" select="NUMHUS"/>
<Student>
<HUSID>
<xsl:value-of select="$husid"/>
</HUSID>
<SURNAME>
<xsl:value-of select="$surname"/>
</SURNAME>
<xsl:apply-templates select="/dataroot/Student[HUSID/text()=$husid]" mode="instanceperiod" />
</Student>
</xsl:template>
<xsl:template match="Student" mode="instanceperiod">
<xsl:variable name="courseid" select="COURSEID"/>
<xsl:variable name="numhus" select="NUMHUS"/>
<Instance>
<NUMHUS>
<xsl:value-of select="$numhus"/>
</NUMHUS>
<InstancePeriod>
<COURSEID>
<xsl:value-of select="$courseid"/>
</COURSEID>
</InstancePeriod>
</Instance>
</xsl:template>
</xsl:stylesheet>
Code: Select all
<dataroot>
<Student>
<HUSID>idno</HUSID>
<SURNAME>Second Name</SURNAME>
<Instance>
<NUMHUS>idno2</NUMHUS>
<InstancePeriod>
<COURSEID>course1</COURSEID>
</InstancePeriod>
</Instance>
<Instance>
<NUMHUS>idno2</NUMHUS>
<InstancePeriod>
<COURSEID>course2</COURSEID>
</InstancePeriod>
</Instance>
<Instance>
<NUMHUS>idno2</NUMHUS>
<InstancePeriod>
<COURSEID>course3</COURSEID>
</InstancePeriod>
</Instance>
</Student>
</dataroot>
However, the output I want is as follows:
Code: Select all
<dataroot>
<Student>
<HUSID>idno</HUSID>
<SURNAME>Second Name</SURNAME>
<Instance>
<NUMHUS>idno2</NUMHUS>
<InstancePeriod>
<COURSEID>course1</COURSEID>
<COURSEID>course2</COURSEID>
<COURSEID>course3</COURSEID>
</InstancePeriod>
</Instance>
</Student>
</dataroot>