public static String stripFormattingfromXMLString ( String xml ) { try { Document document = DocumentUtilities . toDocument ( xml ) ; DOMImplementationRegistry registry = DOMImplementationRegistry . newInstance ( ) ; DOMImplementationLS domImplementationLS = ( DOMImplementationLS ) registry . getDOMImplementation ( "LS" ) ; LSSerializer serializaer = domImplementationLS . createLSSerializer ( ) ; serializaer . getDomConfig ( ) . setParameter ( "format-pretty-print" , Boolean . FALSE ) ; serializaer . getDomConfig ( ) . setParameter ( "xml-declaration" , Boolean . TRUE ) ; // otherwise UTF-16 is used by default LSOutput lsOutput = domImplementationLS . createLSOutput ( ) ; lsOutput . setEncoding ( "UTF-8" ) ; ByteArrayOutputStream byteStream = new ByteArrayOutputStream ( ) ; lsOutput . setByteStream ( byteStream ) ; serializaer . write ( document , lsOutput ) ; return new String ( byteStream . toByteArray ( ) , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } catch ( ClassCastException e ) { throw new RuntimeException ( e ) ; } }
Strips formatting from an XML String