e520. writing only the text of a dom document.txt

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

TXT
41
字号
One of the three output methods of a transformer is text. With this output method, only the text in CharacterData nodes are written out. Comments are also written out since they are CharacterData nodes. To remove the comments, see e544 Removing a Node from a DOM Document. 
    // 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.METHOD, "text");
    
        // 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"?>
    <root>
        <!-- comment -->
        <?target instructions?>
        <elem1 attr="attrValue">
            cat &lt; <elem2> dog </elem2> rat
        </elem1>
        <![CDATA[cat < dog > rat]]>
    </root>

The resulting output from running the example is: 
    
    <!-- comment -->
    
    
        cat <  dog  rat
    
    cat < dog > rat

⌨️ 快捷键说明

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