In the previous example, we used two separate input files, but the same result can be created with just one file. First, the two files are concatenated and another node is added to act as a parent node. Here’s the input data:
Combined XML File (combined.xml
):
<data>
<employees>
<employee>
<id>1</id>
<hourly-rate>20</hourly-rate>
</employee>
<employee>
<id>2</id>
<hourly-rate>25</hourly-rate>
</employee>
</employees>
<labor>
<entry>
<id>1</id>
<date>2024-10-01</date>
<hours>8</hours>
</entry>
<entry>
<id>1</id>
<date>2024-10-02</date>
<hours>7</hours>
</entry>
<entry>
<id>2</id>
<date>2024-10-01</date>
<hours>6</hours>
</entry>
</labor>
</data>
In this case, the XSLT does not need to use the <xsl:merge>
instruction because all the data is already within the same XML document. Instead, we can simply access the nodes and join the data based on the id
.
Updated XSLT Code for the Single File:
<xsl:stylesheet version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- Match the root element -->
<xsl:template match="/data">
<employees-summary>
<!-- Iterate over each employee -->
<xsl:for-each select="employees/employee">
<employee>
<id><xsl:value-of select="id"/></id>
<total-hours>
<!-- Sum the hours worked by the current employee -->
<xsl:value-of select="sum(/data/labor/entry[id
= current()/id]/hours)"/>
</total-hours>
<hourly-rate>
<!-- Output the hourly rate for the current employee -->
<xsl:value-of select="hourly-rate"/>
</hourly-rate>
<total-earnings>
<!-- Calculate total earnings (total hours * hourly rate) -->
<xsl:value-of select="sum(/data/labor/entry[id
= current()/id]/hours) * hourly-rate"/>
</total-earnings>
</employee>
</xsl:for-each>
</employees-summary>
</xsl:template>
</xsl:stylesheet>
Explanation:
/data/employees/employee
: Selects the employee nodes from the combined file.sum(/data/labor/entry[id = current()/id]/hours)
: Calculates the total hours by summing up thehours
values in thelabor/entry
elements where theid
matches the current employee’sid
.hourly-rate
: Outputs the employee’s hourly rate from theemployee
element.- Total earnings: This is computed by multiplying the total hours worked by the employee’s hourly rate.
The resulting output will include each employee’s ID, total hours worked, hourly rate, and total earnings in the desired format.