A DOM program that writes Fibonacci numbers into an XML document


import java.math.*;
import java.io.*;
import org.w3c.dom.*;
import org.apache.xerces.dom.*;


public class FibonacciDOM {

  public static void main(String[] args) {
   
    try {
      
      DOMImplementationImpl impl = (DOMImplementationImpl) 
       DOMImplementationImpl.getDOMImplementation();
       
      DocumentType type = impl.createDocumentType("Fibonacci_Numbers",
       null, null);
      
      // type is supposed to be able to be null, 
      // but in practice that didn't work                     
      DocumentImpl fibonacci 
       = (DocumentImpl) impl.createDocument(null, "Fibonacci_Numbers", type);
      
      BigInteger low  = BigInteger.ZERO;
      BigInteger high = BigInteger.ONE;      
      
      Element root = fibonacci.createElement("Fibonacci_Numbers");
      // This not only creates the element; it also makes it the
      // root element of the document. 

      for (int i = 0; i < 101; i++) {
        Element number = fibonacci.createElement("fibonacci");
        number.setAttribute("index", Integer.toString(i));
        Text text = fibonacci.createTextNode(low.toString());
        number.appendChild(text);
        root.appendChild(number);
        BigInteger temp = high;
        high = high.add(low);
        low = temp;
      }
      
      // Now that the document is created we need to *serialize* it
      
      
 
    }
    catch (DOMException e) {
      e.printStackTrace();
    }

  }

}

Previous | Next | Top | Cafe con Leche

Copyright 2000 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified February 22, 2000