//DOMNodes.java //Programming XML in Java //Gerard Uffelman import org.w3c.dom.*; import org.apache.xerces.parsers.DOMParser; import java.io.FileOutputStream; //Output file stream import java.io.PrintStream; //Wrapper for FileOutputStream import java.io.IOException; //to catch user io errors //This is the application class, it checks the input arguments, opens //the output file, creates a NodePrinter class and intstructs it to //parse the input file and print the results. public class DOMNodes { public static void main(String[] args) { FileOutputStream fos; PrintStream ps; //wrapper for fos int nodeSize = 0; //maximum node size entered //Check number of input parameters if(args.length <= 2 || args.length > 3) { System.err.println("Invalid Command: Wrong number of arguments!"); System.err.println("Usage:\tjava SaxNodes graphFile nodeSize outputFile"); System.exit(0); } //Retrieve / Convert input integer try{ Integer intWrapper = new Integer( args[1] ); nodeSize = intWrapper.intValue(); } catch(NumberFormatException nfe) { System.err.println("Error, invalid number: " + args[1]); return; } //Attempt to open file for output try{ fos = new FileOutputStream( args[2] ); } catch(IOException ioe) { System.err.println("Can't open output file: " + args[2]); return; } //instantiate ps with FileOutputStream fos ps = new PrintStream(fos); NodePrinter nptr = new NodePrinter(ps, nodeSize); //Create Node printer object nptr.printNodes(args[0]); //Recursively Traverse DOM tree and print nodes. ps.close(); //close PrintStream } } //NodePrinter class constructor receives PrintStream and Maximum size //of pages to print. class NodePrinter { private PrintStream ps; private int nodeSize; public NodePrinter(PrintStream ps_in, int nodeSize_in) { ps = ps_in; nodeSize = nodeSize_in; } //Create DOMParser object, parse input file, recursively traverse //DOM tree and print the nodes that are lager than nodeSize. public void printNodes(String uri) { try{ DOMParser parser = new DOMParser(); parser.parse(uri); Document doc = parser.getDocument(); traverse_tree(doc, ps, nodeSize); } catch(Exception e){ e.printStackTrace(System.err); } } //This static function is called from the printNodes function or externally. //traverse_tree() is recursive, so we define it as static to make better use //of resources. public static void traverse_tree(Node node, PrintStream ps, int nodeSize) { if(node == null){ return; } int type = node.getNodeType(); switch(type) { /*Document Root node encountered. Write opening HTML tags, start unordered list, recursively process child nodes, and write closing HTML tags */ case Node.DOCUMENT_NODE: { ps.println(""); ps.println("
"); ps.println("