public static String escapeForXML ( String source ) { Args . nullNotPermitted ( source , "source" ) ; StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < source . length ( ) ; i ++ ) { char c = source . charAt ( i ) ; switch ( c ) { case ' ' : { sb . append ( "&lt;" ) ; break ; } case ' ' : { sb . append ( "&gt;" ) ; break ; } case ' ' : { String next = source . substring ( i , Math . min ( i + 6 , source . length ( ) ) ) ; if ( next . startsWith ( "&lt;" ) || next . startsWith ( "&gt;" ) || next . startsWith ( "&amp;" ) || next . startsWith ( "&apos;" ) || next . startsWith ( "&quot;" ) ) { sb . append ( c ) ; } else { sb . append ( "&amp;" ) ; } break ; } case ' ' : { sb . append ( "&apos;" ) ; break ; } case ' ' : { sb . append ( "&quot;" ) ; break ; } default : sb . append ( c ) ; } } return sb . toString ( ) ; }
Returns a new string where any special characters in the source string have been encoded .