Friday, September 11, 2009

How to Remove All Empty Nodes from XML Payload

Empty nodes in an XML payload increases payload size and may be the reason for XML parsing errors. You can add conditional logic to handle empty nodes in transformations but it’s not feasible for big XML payloads. Adding if/switch conditions for transforming big XML payloads is time consuming and error prone too. It requires a throughout testing to verify whether all the conditional logic is applied correctly or not.


For big XML payloads you can use a separate XSLT transformation to handle all the empty nodes. It will save your time to add conditional logic to handle empty nodes in every transformation. It incurs a little performance overhead but save lot of time and efforts to add/debug/test/re-test condition logic for empty nodes.


See the script given underneath; it can handle all empty nodes in an XML payload:


<xsl:template match="node()">
<xsl:if test="count(descendant::text()[string-length(normalize-space(.))>0]|@*)">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:if>
</xsl:template>

<xsl:template match="@*">
<xsl:copy/>
</xsl:template>

<xsl:template match="text()">
<xsl:value-of select="normalize-space(.)"/>
</xsl:template>

Steps to use this script in BPEL:

  • Drag and drop a Transform activity and select the XML payload, from which you want to remove empty nodes. Select same XML document for source and target.
  • Create an empty transformation file and go to the source view.
  • Replace the XSLT fragment given below with the XSLT script given above:


<xsl:template match="/">

</xsl:template>

  • Now you all set, save and deploy your BPEL process, XSLT map and do a sanity test.