tomaytotomato
tomaytotomato

Reputation: 4028

Replacing substring inside string not working? Java XML

All,

I am storing SQL queries as XML for my java application to improve maintainability.

Parts of my query require parameterisation, therefore I have created identifiers that I can use to replace with values when I create my query string.

e.g.

WHERE CB.callback_date >= TO_DATE('$LASTDATE$','DD/MM/YYYY')
  AND CB.callback_date < TO_DATE('$FROMDATE$','DD/MM/YYYY')

I have a function in my application that will replace these substrings.

public static String xmlQueryPrep(String prep)
{

    //add dates to query
    prep.replace("'$LASTDATE$'", "'20/10/2013'");
    prep.replace("'$FROMDATE$'", "'18/10/2013'");
    prep.replace("&lt;", "<").replace("&gt;", ">");
    return prep;    
}

For some reason it is replacing the ASCII codes for < and > but it is not replacing my markup

Output

WHERE CB.callback_date >= TO_DATE('$LASTDATE$','DD/MM/YYYY')
  AND CB.callback_date < TO_DATE('$FROMDATE$','DD/MM/YYYY')

Why is it not replacing correctly?

Upvotes: 0

Views: 267

Answers (1)

Alexis C.
Alexis C.

Reputation: 93842

Strings in Java are immutables.

An object is considered immutable if its state cannot change after it is constructed

If you take a look at the documentation, you will see that each method that is applied to a String to modify its content will return a new String.

You should do :

prep = prep.replace("'$LASTDATE$'", "'20/10/2013'");
prep = prep.replace("'$FROMDATE$'", "'18/10/2013'");
prep = prep.replace("&lt;", "<").replace("&gt;", ">");
return prep;  

Or even better (method chaining):

return prep.replace("'$LASTDATE$'", "'20/10/2013'")
           .replace("'$FROMDATE$'", "'18/10/2013'")
           .replace("&lt;", "<")
           .replace("&gt;", ">");

Upvotes: 7

Related Questions