e519. emitting a doctype declaration when writing an xml file from a dom document.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 37 行

TXT
37
字号
By default, the DOCTYPE is not written when using a transformer to dump a DOM document to an XML file. This example demonstrates how to write a DOCTYPE with a public and system id. Unfortunately, it is not possible to write a DOCTYPE with an internal DTD. 
    // Create a document; this method is implemented in
    // e510 The Quintessential Program to Create a DOM Document from an XML File
    Document doc = parseXmlFile("infilename.xml", false);
    
    try {
        // Create a transformer
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
    
        // Set the public and system id
        xformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "publicId");
        xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "systemId");
    
        // Write the DOM document to a file
        Source source = new DOMSource(doc);
        Result result = new StreamResult(new File("outfilename.xml"));
        xformer.transform(source, result);
    } catch (TransformerConfigurationException e) {
    } catch (TransformerException e) {
    }

This is the sample input for the example: 
    <?xml version="1.0" encoding="UTF-8"?>
    <map>
        <entry key="key1" value="value1" />
        <entry key="key2" />
    </map>

The resulting XML from running the example is: 
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE map PUBLIC "publicId" "systemId">
    <map>
        <entry key="key1" value="value1"/>
        <entry key="key2"/>
    </map>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?