different between “getDocumentElement” and “getFirstChild”

前端 未结 1 924
一整个雨季
一整个雨季 2021-02-19 21:05

I have the following Document object - Document myDoc.

myDoc holds an XML file by...

myDoc = Document         


        
1条回答
  •  走了就别回头了
    2021-02-19 21:47

    The Node you get using myDoc.getFirstChild() may not be the document root if there are other nodes before the document root node - such as a comment node. Look at the example below:

    import org.w3c.dom.*;
    
    public class ReadXML {
    
        public static void main(String args[]) throws Exception{     
    
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    
            // Document elements
            Document doc = docBuilder.parse(new File(args[0]));
    
            Node firstChild = doc.getFirstChild();
            System.out.println(firstChild.getChildNodes().getLength());
            System.out.println(firstChild.getNodeType());
            System.out.println(firstChild.getNodeName());
    
            Node root = doc.getDocumentElement();
            System.out.println(root.getChildNodes().getLength());
            System.out.println(root.getNodeType());
            System.out.println(root.getNodeName());
    
        }
    }
    

    When parsing the following XML file:

    
    
    
       
          
             QWZ5671
             39.95
             
                Red
                Burgundy
             
             
                Red
                Burgundy
             
              
       
    
    

    gives the following result:

    0
    8
    #comment
    3
    1
    catalog
    

    But if I remove the comment, it gives:

    3
    1
    catalog
    3
    1
    catalog
    

    0 讨论(0)
提交回复
热议问题