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

时间:2012-11-25 17:40:43

标签: java xml dom doctype

我在java中使用DOM创建了一个XML文档。我无法添加doctype。我想要这样的doctype。

<!DOCTYPE IndInfo PUBLIC "EDAFileSomething" "EDAFileSomething_2_0.dtd">

这是文档创建代码。

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();

这是变形金刚对象代码。

TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = null;
            try {
                transformer = transformerFactory.newTransformer();
            } catch (TransformerConfigurationException ex) {
                Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
            }
            DOMSource source = new DOMSource(doc);
            try {

                StreamResult result = new StreamResult(System.out);
                transformer.transform(source, result);
            } catch (TransformerException ex) {
                Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
            }

            System.out.println("File saved!");

2 个答案:

答案 0 :(得分:11)

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

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);

答案 1 :(得分:1)

如果您通过在DOMImplementation上调用getDOMImplementation()方法获得DocumentBuilder的实例,则可以使用createDocument方法创建新的Document使用指定的doctype。

它还有createDocumentType方法来创建DocumentType对象

有关详细信息,请参阅http://docs.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/DOMImplementation.htmlhttp://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html