to the main page about the tutorial  THE XML REVOLUTION  -  TECHNOLOGIES FOR THE FUTURE WEB back up next

A simple DOM example

The following Java program uses DOM to read the recipe collection and cut it down to the first recipe:

import java.io.*; 
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.*;

public class FirstRecipeDOM {

  public static void main(String[] args) {
    try {
      DOMParser p = new DOMParser();
      p.parse(args[0]);
      Document doc = p.getDocument();
      Node n = doc.getDocumentElement().getFirstChild();
      while (n!=null && !n.getNodeName().equals("recipe")) 
        n = n.getNextSibling();
      PrintStream out = System.out;
      out.println("<?xml version=\"1.0\"?>");
      out.println("<collection>");
      if (n!=null)
        print(n, out);
      out.println("</collection>");
    } catch (Exception e) {e.printStackTrace();}
  }

  static void print(Node node, PrintStream out) {
    int type = node.getNodeType();
    switch (type) {
      case Node.ELEMENT_NODE:
        out.print("<" + node.getNodeName());
        NamedNodeMap attrs = node.getAttributes();
        int len = attrs.getLength();
        for (int i=0; i<len; i++) {
            Attr attr = (Attr)attrs.item(i);
            out.print(" " + attr.getNodeName() + "=\"" +
                      escapeXML(attr.getNodeValue()) + "\"");
        }
        out.print('>');
        NodeList children = node.getChildNodes();
        len = children.getLength();
        for (int i=0; i<len; i++)
          print(children.item(i), out);
        out.print("</" + node.getNodeName() + ">");
        break;
      case Node.ENTITY_REFERENCE_NODE:
        out.print("&" + node.getNodeName() + ";");
        break;
      case Node.CDATA_SECTION_NODE:
        out.print("<![CDATA[" + node.getNodeValue() + "]]>");
        break;
      case Node.TEXT_NODE:
        out.print(escapeXML(node.getNodeValue()));
        break;
      case Node.PROCESSING_INSTRUCTION_NODE:
        out.print("<?" + node.getNodeName());
        String data = node.getNodeValue();
        if (data!=null && data.length()>0)
           out.print(" " + data);
        out.println("?>");
        break;
    }
  }

  static String escapeXML(String s) {
    StringBuffer str = new StringBuffer();
    int len = (s != null) ? s.length() : 0;
    for (int i=0; i<len; i++) {
       char ch = s.charAt(i);
       switch (ch) {
       case '<': str.append("&lt;"); break;
       case '>': str.append("&gt;"); break;
       case '&': str.append("&amp;"); break;
       case '"': str.append("&quot;"); break;
       case '\'': str.append("&apos;"); break;
       default: str.append(ch);
     }
    }
    return str.toString();
  }
}

Note that:

back COPYRIGHT © 2000-2003 ANDERS MØLLER & MICHAEL I. SCHWARTZBACH next