Transforming DOM to file strips out DOCTYPE element

O

O.B.

The code below simply reads in an XML file and prints it back to to a
file. Unfortunately, it drops the !DOCTYPE element. Any clue why this
is happening?

import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;


Document doc = null;
try {
// Create a builder factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
// Create the builder and parse the file
Document doc = factory.newDocumentBuilder().parse(new File(filename));
} catch (SAXException e) {
// A parsing error occurred; the xml input is not valid
} catch (ParserConfigurationException e) {
} catch (IOException e) {
}

// At this point, I have verified that doc.getDoctype points
// to valid data.

// Write data in memory (XML Document) to output stream
FileOutputStream tfos = new FileOutputStream("temp");
Result result = new StreamResult(tfos);
Source source = new DOMSource(hibernateDoc);
try {
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
tfos.close();


// At this point the "temp" file does not have a DOCTYPE element.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top