private String setXmlPreambleAndDTD ( final String xml , final String dtdFileName , final String entities , final String dtdRootEleName ) { // Check if the XML already has a DOCTYPE. If it does then replace the values and remove entities for processing final Matcher matcher = DOCTYPE_PATTERN . matcher ( xml ) ; if ( matcher . find ( ) ) { String preamble = matcher . group ( "Preamble" ) ; String name = matcher . group ( "Name" ) ; String systemId = matcher . group ( "SystemId" ) ; String declaredEntities = matcher . group ( "Entities" ) ; String doctype = matcher . group ( ) ; String newDoctype = doctype . replace ( name , dtdRootEleName ) ; if ( systemId != null ) { newDoctype = newDoctype . replace ( systemId , dtdFileName ) ; } if ( declaredEntities != null ) { newDoctype = newDoctype . replace ( declaredEntities , " [\n" + entities + "\n]" ) ; } else { newDoctype = newDoctype . substring ( 0 , newDoctype . length ( ) - 1 ) + " [\n" + entities + "\n]>" ; } if ( preamble == null ) { final StringBuilder output = new StringBuilder ( ) ; output . append ( "<?xml version='1.0' encoding='UTF-8' ?>\n" ) ; output . append ( xml . replace ( doctype , newDoctype ) ) ; return output . toString ( ) ; } else { return xml . replace ( doctype , newDoctype ) ; } } else { // The XML doesn't have any doctype so add it final String preamble = XMLUtilities . findPreamble ( xml ) ; if ( preamble != null ) { final StringBuilder doctype = new StringBuilder ( ) ; doctype . append ( preamble ) ; appendDoctype ( doctype , dtdRootEleName , dtdFileName , entities ) ; return xml . replace ( preamble , doctype . toString ( ) ) ; } else { final StringBuilder output = new StringBuilder ( ) ; output . append ( "<?xml version='1.0' encoding='UTF-8' ?>\n" ) ; appendDoctype ( output , dtdRootEleName , dtdFileName , entities ) ; output . append ( xml ) ; return output . toString ( ) ; } } }
Sets the DTD for an xml file . If there are any entities then they are removed . This function will also add the preamble to the XML if it doesn t exist .