Emitting a DOCTYPE Declaration When Writing an XML File from a DOM Document : DOCTYPE « XML « Java Tutorial






import java.io.File;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

public class Main {
  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);

    factory.setExpandEntityReferences(false);

    Document doc = factory.newDocumentBuilder().parse(new File("filename"));

    Transformer xformer = TransformerFactory.newInstance().newTransformer();

    xformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "publicId");
    xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "systemId");

    Source source = new DOMSource(doc);
    Result result = new StreamResult(new File("outfilename.xml"));
    xformer.transform(source, result);
  }
}








33.25.DOCTYPE
33.25.1.Emitting a DOCTYPE Declaration When Writing an XML File from a DOM Document