public static String serialize ( Node node , boolean withXmlDeclaration ) { if ( node == null ) { return "" ; } try { LSOutput output = LS_IMPL . createLSOutput ( ) ; StringWriter result = new StringWriter ( ) ; output . setCharacterStream ( result ) ; LSSerializer serializer = LS_IMPL . createLSSerializer ( ) ; serializer . getDomConfig ( ) . setParameter ( "xml-declaration" , withXmlDeclaration ) ; serializer . setNewLine ( "\n" ) ; String encoding = "UTF-8" ; if ( node instanceof Document ) { encoding = ( ( Document ) node ) . getXmlEncoding ( ) ; } else if ( node . getOwnerDocument ( ) != null ) { encoding = node . getOwnerDocument ( ) . getXmlEncoding ( ) ; } output . setEncoding ( encoding ) ; serializer . write ( node , output ) ; return result . toString ( ) ; } catch ( Exception ex ) { LOGGER . warn ( "Failed to serialize node to XML String: [{}]" , ex . getMessage ( ) ) ; return "" ; } }
Serialize a DOM Node into a string with an optional XML declaration at the start .