public static String escapeForXML ( final String content ) { if ( content == null ) return "" ; /* * Note: The following characters should be escaped: & < > " ' * * However, all but ampersand pose issues when other elements are included in the title. * * eg <title>Product A > Product B<phrase condition="beta">-Beta</phrase></title> * * should become * * <title>Product A &gt; Product B<phrase condition="beta">-Beta</phrase></title> */ String fixedContent = XMLUtilities . STANDALONE_AMPERSAND_PATTERN . matcher ( content ) . replaceAll ( "&amp;" ) ; // Loop over and find all the XML Elements as they should remain untouched. final LinkedList < String > elements = new LinkedList < String > ( ) ; if ( fixedContent . indexOf ( ' ' ) != - 1 ) { int index = - 1 ; while ( ( index = fixedContent . indexOf ( ' ' , index + 1 ) ) != - 1 ) { int endIndex = fixedContent . indexOf ( ' ' , index ) ; int nextIndex = fixedContent . indexOf ( ' ' , index + 1 ) ; /* * If the next opening tag is less than the next ending tag, than the current opening tag isn't a match for the next * ending tag, so continue to the next one */ if ( endIndex == - 1 || ( nextIndex != - 1 && nextIndex < endIndex ) ) { continue ; } else if ( index + 1 == endIndex ) { // This is a <> sequence, so it should be ignored as well. continue ; } else { elements . add ( fixedContent . substring ( index , endIndex + 1 ) ) ; } } } // Find all the elements and replace them with a marker String escapedTitle = fixedContent ; for ( int count = 0 ; count < elements . size ( ) ; count ++ ) { escapedTitle = escapedTitle . replace ( elements . get ( count ) , "###" + count + "###" ) ; } // Perform the replacements on what's left escapedTitle = escapedTitle . replace ( "<" , "&lt;" ) . replace ( ">" , "&gt;" ) . replace ( "\"" , "&quot;" ) ; // Replace the markers for ( int count = 0 ; count < elements . size ( ) ; count ++ ) { escapedTitle = escapedTitle . replace ( "###" + count + "###" , elements . get ( count ) ) ; } return escapedTitle ; }
Escapes a String so that it can be used in a Docbook Element ensuring that any entities or elements are maintained .