且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用DOM(JAVA)在XML文档中添加Doctype

更新时间:2023-11-24 20:13:58

您可以使用DOM构建doctype并设置doctype作为输出属性。

You can construct the doctype with the DOM and set the doctype as an output property.

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
DOMImplementation domImpl = document.getImplementation();
DocumentType doctype = domImpl.createDocumentType("doctype",
    "-//Oberon//YOUR PUBLIC DOCTYPE//EN",
    "YOURDTD.dtd");
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId());
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId());
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File(database));
transformer.transform(source, result);