private boolean removeComments ( DocumentBuilder parser , Document doc ) { try { // Check for the traversal module DOMImplementation impl = parser . getDOMImplementation ( ) ; if ( ! impl . hasFeature ( "traversal" , "2.0" ) ) { // DOM implementation does not support traversal unable to remove comments return false ; } Node root = doc . getDocumentElement ( ) ; DocumentTraversal traversable = ( DocumentTraversal ) doc ; NodeIterator iterator = traversable . createNodeIterator ( root , NodeFilter . SHOW_COMMENT , null , true ) ; Node node = null ; while ( ( node = iterator . nextNode ( ) ) != null ) { if ( node . getNodeValue ( ) . trim ( ) . compareTo ( "Properties" ) != 0 ) { root . removeChild ( node ) ; } } } catch ( FactoryConfigurationError e ) { return false ; } return true ; }
Removes all comments from the document except for the Properties comment All exceptions are suppressed because this is just a nicety to improve human readability .