Search code examples
javaxmlxsltxalan

How to transform an xml file by searching for some nodes and replacing the values


This is the input xml -

<payload id="001">
    <termsheet>
          <format>PDF</format>
          <city>New York</city>
    </termsheet>
</payload>

We are using Xalan for most of our xml transformations and we are on XSLT 1.0 I want to write a XSLT template which would convert the input to the below output -

<payload id="001">
    <termsheet>
          <format>pdf</format>
          <city>Mr. ABC</city>
    </termsheet>
</payload>

I tried lot of answers on SO, but can't get around this problem.


Apologies for not being clear, toLower was an over simplification. I want to use the city name and invoke a java method which will return a business contact from that city. I have updated the original question


Solution

  • I think that the simplest way is to use java extension with Xalan, you can write a simple java class that implements the business logic you need, and then call it from your xslt. The stylesheet is quite simple

     <xsl:stylesheet version="1.0" 
        xmlns:java="http://xml.apache.org/xalan/java"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        exclude-result-prefixes="java">
    
        <xsl:template match='node() | @*'>
            <xsl:copy>
                <xsl:apply-templates select ='node()|@*'></xsl:apply-templates>
            </xsl:copy>
        </xsl:template>
    
        <xsl:template match="termsheet/city">
            <xsl:copy>
                <xsl:value-of select='java:org.example.Card.getName(.)'/>
            </xsl:copy> 
        </xsl:template> 
    </xsl:stylesheet>
    

    you also neeed to write the java class invoked

    package org.example
    
    public class Card {
    
      public static String getName(String id) {
         // put here your code to get what you need 
         return "Mr. ABC"
      }
    }
    

    there are other ways to do that and you should really give an eye to the documentation about xalan extensions