static public void simplify(Node node){
  NodeList children=node.getChildNodes();
  int i=0;
  int len=children.getLength();
  Node prevTextChild=null;
  while (i < len) {
    Node child=children.item(i);
    if (child.hasChildNodes()) {
      simplify(child);
      prevTextChild=null;
      i++;
    }
 else {
      int type=child.getNodeType();
      if (type == Node.PROCESSING_INSTRUCTION_NODE) {
        node.removeChild(child);
        len--;
      }
 else       if (type == Node.COMMENT_NODE) {
        node.removeChild(child);
        len--;
      }
 else       if (type == Node.TEXT_NODE || type == Node.CDATA_SECTION_NODE) {
        if (prevTextChild != null) {
          CharacterData ptc=(CharacterData)prevTextChild;
          ptc.setData(ptc.getNodeValue() + child.getNodeValue());
          node.removeChild(child);
          len--;
        }
 else {
          prevTextChild=child;
          i++;
        }
      }
 else {
        prevTextChild=null;
        i++;
      }
    }
  }
}

static public void simplify ( Node node ) { NodeList children = node . getChildNodes ( ) ; int i = 0 ; int len = children . getLength ( ) ; Node prevTextChild = null ; while ( i < len ) { Node child = children . item ( i ) ; if ( child . hasChildNodes ( ) ) { simplify ( child ) ; prevTextChild = null ; i ++ ; } else { int type = child . getNodeType ( ) ; if ( type == Node . PROCESSING_INSTRUCTION_NODE ) { node . removeChild ( child ) ; len -- ; } else if ( type == Node . COMMENT_NODE ) { node . removeChild ( child ) ; len -- ; } else if ( type == Node . TEXT_NODE || type == Node . CDATA_SECTION_NODE ) { if ( prevTextChild != null ) { CharacterData ptc = ( CharacterData ) prevTextChild ; ptc . setData ( ptc . getNodeValue ( ) + child . getNodeValue ( ) ) ; node . removeChild ( child ) ; len -- ; } else { prevTextChild = child ; i ++ ; } } else { prevTextChild = null ; i ++ ; } } } }
removes comments and processing instruction , and then unites adjacent text nodes . note that cdata sections count as text nodes .
