mercury worlds

ILE RPG ReplaceXmlEntities()

| Comments

Use this subprocedure when you need to escape common XML entities & (ampersand), < (less than), > (greater than), ‘ (single quote), and ” (double quote). Several web reports I generate using CGIDEV2 are in HTML or XML form, and those special XML characters must be escaped.

Author’s note: please excuse the old SyntaxHIghlighter format. I hope to write a lexer for Pygments.

  1.       // Variables for XML entity replacement.  
  2.      d xmlentities     s              1a   dim(5) ctdata  
  3.      d xmlreplacement  s              4a   dim(5) alt(xmlentities)  
  4.   
  5.       // Prototype.  
  6.      d ReplaceXmlEntities…  
  7.      d                 pr           400a   varying  
  8.      d  invalue                     200a   options(*varsize) const  
  9.   
  10.       // Subprocedure.  
  11.      p ReplaceXmlEntities…  
  12.      p                 b  
  13.   
  14.      d ReplaceXmlEntities…  
  15.      d                 pi           400a   varying  
  16.   
  17.      d  invalue                     200a   options(*varsize) const  
  18.      d lastpos         s             10i 0 inz  
  19.      d start           s             10i 0 inz  
  20.      d workvalue       s            400a   inz varying  
  21.      d z               s             10i 0 inz  
  22.   
  23.       /free  
  24.   
  25.          // See the XMLEntities CTDATA array for list.  
  26.          // Ampersand (&) should be first because that is what all the  
  27.          // other replacements use.  
  28.          workvalue = invalue;  
  29.          for z = 1 to %elem(xmlentities);  
  30.              lastpos = 0;  
  31.              start = 1;  
  32.              lastpos = %scan(xmlentities(z):invalue:start);  
  33.              dow lastpos > 0;  
  34.                  workvalue = %replace(‘&’+%trim(xmlreplacement(z))+’;’ :  
  35.                    workvalue:lastpos:1); // ”:1” overwrites the existing “bad” char  
  36.                  start = lastpos+1;  
  37.                  lastpos = %scan(xmlentities(z):invalue:start);  
  38.              enddo;  
  39.          endfor;  
  40.          return workvalue;  
  41.   
  42.       /end-free  
  43.   
  44.      p ReplaceXmlEntities…  
  45.      p                 e  
  46.   
  47.       // Compile-time data.  
  48.       // This can also be stored in a D-spec array.  
  49. **CTDATA xmlentities  
  50. &amp  
  51. <lt  
  52. >gt  
  53. ‘apos  
  54. “quot  

Feel free to change the size of the invalue, workvalue, and return sizes. I use the procedure over single fields of data which are not very large.

Comments