Java, Software Development

Remove XML Element based on parameter in Java using XSLT

This post shows how to remove an XML element based on some parameters in Java using XSLT. We mean parameters for the Transformer object and let XSLT work its magic during the transformation. Therefore, three significant events will happen. First, we define a parameter and its value in Java using the Transformer object. Second, write an XSLT and use that parameter and its value to exclude an XML element conditionally. Finally, use the Transformer object with the XSLT.


Before we go on, here are the things we used for this post.

  • Java 8 (JDK)
  • IntelliJ IDEA – optional
  • Spring Boot – optional
  • Windows 10 – optional
  • XSLT 1.0

XML whose element we want to remove in Java

Consider the following XML document that has a collection of CDs. Each CD element contains its details like title, artist, company (label record), etc.  For this post, we want to remove all COMPANY XML elements using Java and XSLT during the transformation.

After the transformation, he will have created the following new XML document without the COMPANY elements.

Easy, right? Let us how we can do it in Java using XSLT.

Set Parameters For Transformer Object In Java

The codes below pass parameters to the Transformer object.

XSLT To Remove XML Element With Java codes

For our post, we have the following code snipper in the transformation.xsl file. For our XSLT to work, we created a template to match the COMPANY XML element we want to remove. Then, we use the choose and when operators. These will test the parameter we provided the Transformer object.

Moreover, we use a boolean expression that checks whether the parameter removeCompany is ‘true’ or not. If it is not “true”, we include the COMPANY XML element during the transformation. Otherwise, we exclude the COMPANY element.

Download the Codes

The codes for this post are available on GitHub.


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like