XML Parsing

Traversing the Document

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import org.w3c.dom.*;

public class OrderProcessor {
  public static void main (String args[]) {

    //some code here
    
    doc = db.parse(docFile);

    //STEP 1:  Get the root element
    Element root = doc.getDocumentElement();
    System.out.println("The root element is "+root.getNodeName());
    
    //STEP 2:  Get the children
    NodeList children = root.getChildNodes();
    System.out.println("There are "+children.getLength()
                                  +" nodes in this document.");

    //STEP 3:  Step through the children
    for (Node child = root.getFirstChild(); 
         child != null;
         child = child.getNextSibling())
    {
      //The node name is either the tag name or #text
      System.out.println(child.getNodeName()+" = "+child.getNodeValue());   
    }

    //STEP 4:  Recurse this functionality
    stepThrough(root);


  }

  private static void stepThrough (Node start)
  {
    System.out.println(start.getNodeName()+" = "+start.getNodeValue());

    //if its a node, then print the attributes.
    if (start.getNodeType() == start.ELEMENT_NODE) 
    {   
      NamedNodeMap startAttr = start.getAttributes();
      for (int i = 0; 
           i < startAttr.getLength();
           i++) {
        Node attr = startAttr.item(i);
        System.out.println("  Attribute:  "+ attr.getNodeName()
                           +" = "+attr.getNodeValue());
      }   
    } 
    
    
    for (Node child = start.getFirstChild(); 
         child != null;
         child = child.getNextSibling())
    {
      stepThrough(child);
    }
  }

}

José M. Vidal .

9 of 16