A simple example to show how to use the DOM API : xerces « XML « Java






A simple example to show how to use the DOM API

 
import java.io.*;

import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import org.apache.xerces.parsers.DOMParser;

public class MainClass {
  public void processNode(Node node, String spacer) throws IOException {
    if (node == null)
      return;
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      String name = node.getNodeName();
      System.out.print(spacer + "<" + name);
      NamedNodeMap nnm = node.getAttributes();
      for (int i = 0; i < nnm.getLength(); i++) {
        Node current = nnm.item(i);
        System.out.print(" " + current.getNodeName() + "= " + current.getNodeValue());
      }
      System.out.print(">");
      NodeList nl = node.getChildNodes();
      if (nl != null) {
        for (int i = 0; i < nl.getLength(); i++) {
          processNode(nl.item(i), "");
        }
      }
      System.out.println(spacer + "</" + name + ">");
      break;
    case Node.TEXT_NODE:
      System.out.print(node.getNodeValue());
      break;
    case Node.CDATA_SECTION_NODE:
      System.out.print("" + node.getNodeValue() + "");
      break;
    case Node.ENTITY_REFERENCE_NODE:
      System.out.print("&" + node.getNodeName() + ";");
      break;
    case Node.ENTITY_NODE:
      System.out.print("<ENTITY: " + node.getNodeName() + "> </" + node.getNodeName() + "/>");
      break;
    case Node.DOCUMENT_NODE:
      NodeList nodes = node.getChildNodes();
      if (nodes != null) {
        for (int i = 0; i < nodes.getLength(); i++) {
          processNode(nodes.item(i), "");
        }
      }
      break;
    case Node.DOCUMENT_TYPE_NODE:
      DocumentType docType = (DocumentType) node;
      System.out.print("<!DOCTYPE " + docType.getName());
      if (docType.getPublicId() != null) {
        System.out.print(" PUBLIC " + docType.getPublicId() + " ");
      } else {
        System.out.print(" SYSTEM ");
      }
      System.out.println(" " + docType.getSystemId() + ">");
      break;
    default:
      break;
    }
  }

  public static void main(String[] args) {
    String uri = "test.xml";
    try {
      bookDescDOM bd = new bookDescDOM();
      System.out.println("Parsing XML File: " + uri + "\n\n");
      DOMParser parser = new DOMParser();
      parser.setFeature("http://xml.org/sax/features/validation", true);
      parser.setFeature("http://xml.org/sax/features/namespaces", false);
      parser.parse(uri);
      Document doc = parser.getDocument();
      bd.processNode(doc, "");
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("Error: " + e.getMessage());
    }
  }
}

 








Related examples in the same category

1.Walking a Document with DOM
2.Adding an Element with DOM
3.Adding an Attribute with DOM
4.Outputting a DOM with XMLSerializer
5.Parsing XML with SAX