< 1 minutes read

Long ago I had a requirement to work with XML, where eventually I got a need to apply stylesheet for them. I am sharing my experience on how I implemented XSL if else condition by using choose and otherwise elements.

Requirement: Check whether a node has attributes or it has a string.

Example showing : One of the nodes has 0 File(s) found and the other has attributes such as

<autoincludesystem_info mdate='08/23/2011' mtime='09:51' ampm='PM' filesize='64' filename='AFP_p.tgp' />

Below is a sample of two nodes


	<autoIncludeUser>0 File(s) found</autoIncludeUser>

		<autoincludesystem_info mdate='08/23/2011' mtime='09:51' ampm='PM' filesize='64' filename='AFP_p.tgp' />
		<autoincludesystem_info mdate='08/23/2011' mtime='09:51' ampm='PM' filesize='3,879' filename='AnalystsExpressionMacros.tgp' />
		<autoincludesystem_info mdate='08/23/2011' mtime='09:51' ampm='PM' filesize='475' filename='base64Converter.tgp' />
		<autoincludesystem_info mdate='08/23/2011' mtime='09:51' ampm='PM' filesize='<DIR>' filename='codePages' />

	<autoIncludeStudio>0 File(s) found</autoIncludeStudio>

		<externalLibrarySystem_info mdate='08/23/2011' mtime='09:52' ampm='PM' filesize='196,608' filename='AFPtoXML_DP.dll' />
		<externalLibrarySystem_info mdate='08/23/2011' mtime='09:52' ampm='PM' filesize='13,259' filename='ASN1toXSDRunner.jar' />


How would I identify if a node has just strings or attributes and based on that how can I get the values either String or attribute respectively.

Solution: This is how we can achieve XSL if else condition.

<xsl:when test="something to test">

So here is what I ended up doing

	<xsl:when test="autoIncludeSystem/autoincludesystem_info/@mdate"> <!-- if attribute exists-->

			<table border="1">
						<th>File Name</th>
						<th>File Size</th>
					<xsl:for-each select="autoIncludeSystem/autoincludesystem_info">
							<td valign="top" ><xsl:value-of select="@filename"/></td>
							<td valign="top" ><xsl:value-of select="@filesize"/></td>
							<td valign="top" ><xsl:value-of select="@mdate"/></td>
							<td valign="top" ><xsl:value-of select="@mtime"/></td>
							<td valign="top" ><xsl:value-of select="@ampm"/></td>

	<xsl:otherwise> <!-- if attribute does not exists -->
				<xsl:value-of select="autoIncludeSystem"/>




XSL if else xsl if else condition XSL if else Condition screenshot1

I am not saying that this is the best way to solve, but this is how I implemented XSL If Else condition.

Categories: Programming


I am a Fullstack developer and Consultant with an experience of 9+ years in the industry. I mainly work on Java, React, Javascript, NodeJs, Elasticsearch and Botpress.


Leave a Reply

Avatar placeholder

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.