public static void stripFirstElementInside ( Document document , String parentTagName , String elementTagName ) { NodeList parentNodes = document . getElementsByTagName ( parentTagName ) ; if ( parentNodes . getLength ( ) > 0 ) { Node parentNode = parentNodes . item ( 0 ) ; // Look for a p element below the first parent element Node pNode = parentNode . getFirstChild ( ) ; if ( elementTagName . equalsIgnoreCase ( pNode . getNodeName ( ) ) ) { // Move all children of p node under the root element NodeList pChildrenNodes = pNode . getChildNodes ( ) ; while ( pChildrenNodes . getLength ( ) > 0 ) { parentNode . insertBefore ( pChildrenNodes . item ( 0 ) , null ) ; } parentNode . removeChild ( pNode ) ; } } }
Remove the first element inside a parent element and copy the element s children in the parent .