2012-06-07 11 views
9

Ho il seguente oggetto Document - Document myDoc.diversi tra "getDocumentElement" e "getFirstChild"

myDoc detiene un file XML da ...

myDoc = DocumentBuilderFactory.newInstance() 
      .newDocumentBuilder().parse(file); 

Ora voglio ottenere il root del file XML. C'è qualche differenza tra

Node firstChild = this.myDoc.getFirstChild() 

e

Node firstChild = (Node)myDoc.getDocumentElement() 

Nel primo modo, firstChild detiene una radice il nodo di un file XML ma non avrà la profondità di Node. Tuttavia, nel secondo modo, firstChild sarà la radice con tutta la profondità.

Per esempio, ho il seguente XML

<inventory> 
    <book num="b1"> 
    </book> 
    <book num="b2"> 
    </book> 
    <book num="b3"> 
    </book> 
</inventory> 

e file lo tiene.

Nel primo caso, int count = firstChild.getChildNodes() corrisponde a count = 0.

Il secondo caso darà count = 3.

Ho ragione?

risposta

14

Il nodo che si utilizza myDoc.getFirstChild() potrebbe non essere la radice del documento se ci sono altri nodi prima del nodo radice del documento, ad esempio un nodo di commento. Guardate l'esempio qui sotto:

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()); 

    } 
} 

Durante l'analisi del file XML seguente:

<?xml version="1.0"?> 
<!-- Edited by XMLSpy --> 
<catalog> 
    <product description="Cardigan Sweater" product_image="cardigan.jpg"> 
     <catalog_item gender="Men's"> 
     <item_number>QWZ5671</item_number> 
     <price>39.95</price> 
     <size description="Medium"> 
      <color_swatch image="red_cardigan.jpg">Red</color_swatch> 
      <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch> 
     </size> 
     <size description="Large"> 
      <color_swatch image="red_cardigan.jpg">Red</color_swatch> 
      <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch> 
     </size> 
     </catalog_item>  
    </product> 
</catalog> 

ha pronunciato la seguente risultato:

0 
8 
#comment 
3 
1 
catalog 

Ma se rimuovere il commento, dà:

3 
1 
catalog 
3 
1 
catalog 
+2

ahh quindi il commento ha portato al diff erence .. wow grazie! – URL87