Reputation: 3207
I need to sort the below xml by /parentList/employeesList/personalInfo/middleName
using XSLT. I'm unable to generate the format I'm expecting.The one with Middle name "John" should come up in the output xml. Can you someone help me on this. Below are my XML and XSL's
XML :
<parentList>
<employeesList>
<personalInfo>
<middleName>Mike</middleName>
<lastName>S</lastName>
</personalInfo>
<mailingAddress>
<postalCode>12345</postalCode>
<cityName>CoEmployee CityName</cityName>
<state>PA</state>
<addressLineText>CoEmployee Full Address</addressLineText>
</mailingAddress>
</employeesList>
<employeesList>
<personalInfo>
<middleName>John</middleName>
<lastName>G</lastName>
</personalInfo>
<mailingAddress>
<postalCode>12345</postalCode>
<cityName>CoEmployee CityName</cityName>
<state>PA</state>
<addressLineText>CoEmployee Full Address</addressLineText>
</mailingAddress>
</employeesList>
</parentList>
XSL:
<xsl:template match="parentList">
<xsl:copy>
<xsl:apply-templates>
<xsl:sort select="/employeesList/personalInfo/middleName" order="ascending"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
Upvotes: 1
Views: 50
Reputation: 23627
The problem is in the XPath expression that you are using in your select
attribute. It's an absolute expression (starts with /
) but there your root element is not employeesList
.
When you match parentList
, you apply templates to its children, which provide the context for the sort
element. That means that a relative XPath expression in the select
attribute of sort
should be in the context of employeesList
.
It should work if you simply change your template to this:
<xsl:template match="parentList">
<xsl:copy>
<xsl:apply-templates>
<xsl:sort select="personalInfo/middleName" order="ascending"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
Upvotes: 1
Reputation: 3901
You need to put the sort inside a for-each:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="parentList">
<xsl:for-each select="employeesList">
<xsl:sort select="personalInfo/middleName" order="ascending"/>
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Upvotes: 1