private String cleanHTML ( String content , MacroTransformationContext context ) throws MacroExecutionException { String cleanedContent = content ; HTMLCleanerConfiguration cleanerConfiguration = getCleanerConfiguration ( context ) ; // Note that we trim the content since we want to be lenient with the user in case he has entered // some spaces/newlines before a XML declaration (prolog). Otherwise the XML parser would fail to parse. Document document = this . htmlCleaner . clean ( new StringReader ( cleanedContent ) , cleanerConfiguration ) ; // Since XML can only have a single root node and since we want to allow users to put // content such as the following, we need to wrap the content in a root node: // <tag1> // .. // </tag1> // <tag2> // </tag2> // In addition we also need to ensure the XHTML DTD is defined so that valid XHTML entities can be // specified. // Remove the HTML envelope since this macro is only a fragment of a page which will already have an // HTML envelope when rendered. We remove it so that the HTML <head> tag isn't output. HTMLUtils . stripHTMLEnvelope ( document ) ; // If in inline mode verify we have inline HTML content and remove the top level paragraph if there's one if ( context . isInline ( ) ) { // TODO: Improve this since when're inside a table cell or a list item we can allow non inline items too Element root = document . getDocumentElement ( ) ; if ( root . getChildNodes ( ) . getLength ( ) == 1 && root . getFirstChild ( ) . getNodeType ( ) == Node . ELEMENT_NODE && root . getFirstChild ( ) . getNodeName ( ) . equalsIgnoreCase ( "p" ) ) { HTMLUtils . stripFirstElementInside ( document , HTMLConstants . TAG_HTML , HTMLConstants . TAG_P ) ; } else { throw new MacroExecutionException ( "When using the HTML macro inline, you can only use inline HTML content." + " Block HTML content (such as tables) cannot be displayed." + " Try leaving an empty line before and after the HTML macro." ) ; } } // Don't print the XML declaration nor the XHTML DocType. cleanedContent = HTMLUtils . toString ( document , true , true ) ; // Don't print the top level html element (which is always present and at the same location // since it's been normalized by the HTML cleaner) // Note: we trim the first 7 characters since they correspond to a leading new line (generated by // XMLUtils.toString() since the doctype is printed on a line by itself followed by a new line) + // the 6 chars from "<html>". cleanedContent = cleanedContent . substring ( 7 , cleanedContent . length ( ) - 8 ) ; return cleanedContent ; }
Clean the HTML entered by the user transforming it into valid XHTML .