Page 1 of 1

Replace "personalized" variable

PostPosted: Wed May 10, 2017 9:32 pm
by ClementCvl
Hi,
I have a document that I want replace variables, the problem is that I want use "my variable" instead of basic docx4j variables. My variable are in the format $var$.
I try to adapt that exemple: https://github.com/plutext/docx4j/blob/master/src/samples/docx4j/org/docx4j/samples/VariableReplaceStAX.java
But I have a problem when I calculate the index of the keyEnd because this is the same symbol so it's return a negative value and doesn't replace the variable.
There's a trick to use the same symbol at the beginning and the end of my variable ?
Thank's

Re: Replace "personalized" variable

PostPosted: Wed May 10, 2017 11:16 pm
by ClementCvl
I find the solution, I post it maybe it will help someone.
You need to create a function which can return the length of the string between the 2 delimiter:

Code: Select all
private int lengthVariable(String str){
    String str2 = str;
        for (int i = 0; i < str2.length(); i++){
      if(str2.charAt(i) == '$'){
         str2 = str2.substring(i+1, str2.length());
         break;
      }
   }
   for (int i = 0; i < str2.length(); i++){
      if(str2.charAt(i) == '$'){
         str2 = str2.substring(0, i);
         break;
      }
   }
   return str2.length()+1;
}


After you need to adapt the exemple principally at that line in the replace function:
Code: Select all
int keyEnd = wmlTemplateString.indexOf('}', startKey);

by
Code: Select all
int keyEnd = (startKey + lengthVariable(wmlTemplateString));

And think to change the different delimiter to adapt for your case