SAP CPI – Generic XSLT Mapping to remove Empty Fields and Nodes


min read



I had a recent requirement where I was mapping data from a API to a target API. The API would return a empty tag for a field that has no value, and that would mean my mapping would also create a empty tag. This meant that my target XML also had a empty tag and that was not needed.

XSLT Mapping

<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="*"/>
	<!-- Identity transform -->
	<xsl:template match="@*|node()">
			<xsl:apply-templates select="@*|node()"/>
	<!-- Ignore empty text nodes -->
	<xsl:template match="text()[normalize-space()='']"/>
	<!-- Ignore nodes with only empty nodes or attributes -->
	<xsl:template match="*[not(*|@*|text()[normalize-space()])]"/>
	<!-- Ignore nodes with only empty children -->
	<xsl:template match="*[not(node()[normalize-space()]) and not(text()[normalize-space()]) and not(@*[normalize-space()])]"/>

Test 1

Test 2