How to add XML Prolog to existing XML Java

Viewed 79

I have a set of XML files out of which the prolog has been deleted. In order to further process the files I need to now add this prolog programmatically. My current code is as follows but it does write an empty XML. Can anyone help please?

try(InputStream is = new FileInputStream(FILENAME + filename)){
                DocumentBuilder db = dbf.newDocumentBuilder();
                
                Document doc = db.parse(is);
                doc.appendChild(doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"ISO-8859-1\""));
             
                //print XML
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer transformer = tf.newTransformer();
                DOMSource source = new DOMSource(doc);
                
                FileOutputStream output =
                new FileOutputStream("/Users/XXX/Documents/New/" + filename);
                StreamResult result = new StreamResult(new File(output+filename));
                transformer.transform(source, result);              
            }
1 Answers

The code you have written is fine, but there is small mistake while saving the updated xml to new file new StreamResult(new File(output+filename)) here you are passing FileOutputStream as argument to File()

Actually you don't need to do this just new StreamResult(output) is enough

Complete code:

FileOutputStream output = new FileOutputStream("/Users/XXX/Documents/New/" + filename)
StreamResult result = new StreamResult(output);
transformer.transform(source, result);

Note:

Your code created xml file with filename like this java.io.FileOutputStream@3d82c5f3<filename> in classpath

Related