Skip to Content
Technical Articles

How to remove all empty tags from an XML in SAP PI… It’s Simple!

Hi Guys!

Today I will share a little tip that can be very useful in some cases, how to remove all empty tags from an XML.

In some cases, you need to remove tags that are empty (Ex. <tag> </tag> or <tag/>), and creating this rule in all fields by graphical mapping would be a lot of work.

The tip is to use the code below in your message mapping:

Source code:

public void transform(TransformationInput transformationInput, TransformationOutput transformationOutput) throws StreamTransformationException {
	try {
		InputStream inputstream = transformationInput.getInputPayload().getInputStream();
		OutputStream outputstream = transformationOutput.getOutputPayload().getOutputStream();

		byte[] b = new byte[inputstream.available()];;
		String encoding ="UTF-8";
		String inputXML=new String(b);

		inputXML = inputXML.replaceAll("<\\s*[\\w:]+?\\s*\\/>", "");
		inputXML = inputXML.replaceAll("<\\s*[\\w:]+>(<\\/?\\w+>)*<\\/\\s*[\\w:]+>", "");

	} catch (Exception exception) {
		throw new StreamTransformationException(exception.toString());



Below is an example of the mapping performed, where the field <complemento2\> was removed:


Another Solution (XSLT)

It’s possibile use another solution, a XSLT mapping, below the source code of an XSLT shared by our colleague @Evgeniy Kolmakov.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="node()|@*">
            <xsl:apply-templates select="node()|@*"/>
    <xsl:template match="*[not(@*|*|comment()|processing-instruction()) and normalize-space()='']"/>

I recommend testing both solutions to see which one best applies to your project.


  1. You can use this code and roles in graphical mapping
  2. The java code is executed after the graphical mapping.
  3. If you want to remove only one field, apply the role below in your field:

I hope I helped you with this little tip… 😀



You must be Logged on to comment or reply to a post.