Walking a Document with DOM : xerces « XML « Java






Walking a Document with DOM

 

import org.apache.xerces.parsers.DOMParser;
import org.xml.sax.SAXException;
import java.io.IOException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;

public class MainClass {
  public static void main(String args[]) throws IOException, SAXException {
    DOMParser parser = new DOMParser();
    parser.parse("games.xml");
    Document dom = parser.getDocument();
    walkNode(dom.getDocumentElement());
  }

  private static void walkNode(Node theNode) {
    NodeList children = theNode.getChildNodes();
    printNode(theNode);
    for (int i = 0; i < children.getLength(); i++) {
      Node aNode = children.item(i);
      if (aNode.hasChildNodes())
        walkNode(aNode);
      else
        printNode(aNode);
    }
  }
  private static void printNode(Node aNode) {
    System.out.println(aNode.getNodeName() + "," + aNode.getNodeValue());
  }
}

 








Related examples in the same category

1.Adding an Element with DOM
2.Adding an Attribute with DOM
3.Outputting a DOM with XMLSerializer
4.Parsing XML with SAX
5.A simple example to show how to use the DOM API