e542. adding a processing instruction to a dom document.txt

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

TXT
35
字号
// Obtain an XML 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);
    
    // Add a PI at the beginning of the document
    Element element = doc.getDocumentElement();
    ProcessingInstruction pi = doc.createProcessingInstruction("target", "instruction");
    element.getParentNode().insertBefore(pi, element);
    
    // Find all elements with the name "entry" and add a child PI
    NodeList list = doc.getElementsByTagName("entry");
    for (int i=0; i<list.getLength(); i++) {
        element = (Element)list.item(i);
        pi = doc.createProcessingInstruction("target", "instruction="+i);
    
        // Add the comment to this element
        element.appendChild(pi);
    }

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"?>
    <?target instruction?>
    <map>
        <entry key="key1" value="value1"><?target instruction=0?></entry>
        <entry key="key2"><?target instruction=1?></entry>
    </map>

⌨️ 快捷键说明

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