e1073. getting the root element in a dom document.txt

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

TXT
20
字号
The root element of an XML file is not the same as the root element of a DOM document. In particular, the XML root element is a child of the DOM's root element. The reason is that the XML root element can have siblings, such as a DocumentType or a Comment node. The XML root node can be found by looking for an element node among the children of the DOM's root node. However, there is a convenient method, Document.getDocumentElement(), that does the same thing. This example demonstrates both methods: 
    // 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);
    
    Element root = null;
    
    // Get the XML root node by examining the children nodes
    NodeList list = doc.getChildNodes();
    for (int i=0; i<list.getLength(); i++) {
        if (list.item(i) instanceof Element) {
            root = (Element)list.item(i);
            break;
        }
    }
    
    // Get the XML root node the easy way
    root = doc.getDocumentElement();

⌨️ 快捷键说明

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