2012-06-07 18 views
9

Tengo el siguiente objeto Document - Document myDoc.diferente entre "getDocumentElement" y "getFirstChild"

myDoc mantiene un archivo XML por ...

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

Ahora quiero conseguir la raíz del archivo XML. ¿Hay alguna diferencia entre

Node firstChild = this.myDoc.getFirstChild() 

y

Node firstChild = (Node)myDoc.getDocumentElement() 

En la primera forma, firstChild posee un nodo raíz de un archivo XML pero no va a tener la profundidad de Node. Sin embargo, en la segunda forma, firstChild será la raíz con toda la profundidad.

Por ejemplo, tengo el siguiente código XML

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

y file lo sostiene.

En el primer caso, int count = firstChild.getChildNodes() da count = 0.

La segunda caja dará count = 3.

¿Estoy en lo cierto?

Respuesta

14

El nodo que obtiene utilizando myDoc.getFirstChild() puede no ser la raíz del documento si hay otros nodos antes del nodo raíz del documento, como un nodo de comentario. Mira el siguiente ejemplo:

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

    } 
} 

Al analizar el siguiente archivo XML:

<?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> 

da el siguiente resultado:

0 
8 
#comment 
3 
1 
catalog 

Pero si quito el comentario, se da:

3 
1 
catalog 
3 
1 
catalog 
+2

ahh por lo que el comentario llevó a la diferencia erence .. wow gracias! – URL87

Cuestiones relacionadas