簡體   English   中英

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

[英]How to add Doctype in XML document using DOM (JAVA)

我在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();

這是Transformer對象代碼。

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

您可以使用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);

如果通過在DocumentBuilder上調用getDOMImplementation()方法獲得DOMImplementation實例,則可以使用createDocument方法創建具有指定doctype的新Document

它還有一個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了解更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM