Sort by key in SAP PI

This blog will provide step-by-step guide on how to sort by key in SAP PI. Sometime we get the requirement where incoming data is not properly sorted and data need to be in proper order while sending to target system.

I have listed 2 option here which can be used in SAP PI depending on requirement and structure.

Option 1: Using sort and sortByKey node functions

We can use the sort or sortByKey functions from Node Functions in graphical mapping. Unfortunately we will have to use this function in the mapping for each relevant field – there is no option for pre-sorting whole XML structure using Graphical mapping.

Suppose we have an incoming data coming as below.

SC1_DT

Suppose ReportID is our key for sorting XML. We need to map it using sort function

 

SC2_Sort

Now using we need to use sortBykey for all other fields so that it will be sorted based on ReportID.

SC3_Sortbykey

 

Let’s test the mapping

SC4_Test

 

 

 

 

 

You will notice that Amount and Reference field highlighted above is still not sorted because we have not used sortBykey mapping, so we need to put sortByKey function in all fields which needs to be sorted.

This option can be used in case you have small structure.

 Option 2: Using XSL mapping

This option is really easy and simple when it comes to pre-sorting whole XML. If structure has many fields then using sort or sortBykey will be difficult.

Lets take the same data as example

SC1_DT

XSLT Code which we will be using:

<?xml version=”1.0″ encoding=”utf-8″?>

<xsl:stylesheet version=”1.0″ xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”>

<xsl:output method=”xml” indent=”yes”/>

 <xsl:template match=”@*|node()”>

<xsl:copy>

<xsl:apply-templates select=”@*|node()”>

<xsl:sort select=”ReportID” order =”ascending”/>

</xsl:apply-templates>

</xsl:copy>

</xsl:template>

</xsl:stylesheet>

 

Import XSLT code into SAP PI as imported achive and use in Operation Mapping

Op2_XSLT_Mapping

Lets test the xslt mapping.

Op2_TestingResult

 

2 thoughts to “Sort by key in SAP PI”

  1. Siva Bala says:

    I have this requirement in one of my XML message….I tried copying this code but it is not sorting by the field I intended the sort for.

Leave a Reply

Your email address will not be published. Required fields are marked *

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