public static String getElementText ( Element elem ) { StringBuilder result = new StringBuilder ( ) ; NodeList nodeList = elem . getChildNodes ( ) ; for ( int index = 0 ; index < nodeList . getLength ( ) ; index ++ ) { Node childNode = nodeList . item ( index ) ; if ( childNode != null && ( childNode instanceof Text ) ) { result . append ( " " ) ; result . append ( ( ( Text ) childNode ) . getData ( ) ) ; } } return result . toString ( ) . trim ( ) ; }
Get the concatenated value of all Text nodes that are immediate children of the given Element . If the element has no content it will not have a child Text node . If it does have content it will usually have a single child Text node . But in rare cases it could have multiple child Text nodes . If multiple child Text nodes are found their content is concatenated into a single string each separated by a single space . The value returned is trimmed of beginning and ending whitespace . If the element has no child Text nodes or if all child Text nodes are empty or have whitespace - only values an empty string is returned .