// Read a Graph from XML File import java.io.*; import java.net.*; import java.util.*; import mit16_410_13.*; class Ps2XMLGraph { Hashtable vertices; Ps2XMLGraph () { vertices = new Hashtable(); } public Dictionary readGraph (String path) { XMLStream strm; FileInputStream istrm=null; try { Ps2Vertex currentVertex=null; boolean ingraph=false; istrm=new FileInputStream(path); strm=new XMLStream(istrm, System.out); System.out.println("Reading from "+path); String txt=strm.readText(); // Read any preceding text for (XMLTag atag=strm.readNextTag(); atag!=null; atag=strm.readNextTag()) { String tagid=atag.getTagID(); if (tagid.equals("GRAPH")) { if (ingraph) System.out.println("Nested GRAPH not allowed\n"); ingraph=true; } else if (tagid.equals("/GRAPH")) { if (ingraph) ingraph=false; else System.out.println("/GRAPH not in a GRAPH"); } else if (tagid.equals("VERTEX")) { if (ingraph) currentVertex=findVertexCreate(atag.getAttribute("name")); else { System.out.println("VERTEX not in a GRAPH"); ingraph=true; // recover currentVertex=findVertexCreate(atag.getAttribute("name")); } } else if (tagid.equals("/VERTEX")) { currentVertex=null; } else if (tagid.equals("EDGE")) { if (currentVertex==null) { System.out.println("Edge not embedded in a vertex\n"); } else { Ps2Vertex tovertex=findVertexCreate(atag.getAttribute("vertex")); currentVertex.addEdge(new Ps2Edge(tovertex)); } } else if (tagid.equals("/EDGE")) { } // Nothing to do else { System.out.println("Unknown Tag: "); atag.writeTag(strm); } txt=strm.readText(); } } catch (Exception e) { System.out.println("Exception: "+e.toString()); } finally { try { if (istrm!=null) istrm.close(); } catch (Exception e) {} } return vertices; } Ps2Vertex findVertexCreate (String name) { Ps2Vertex nd=(Ps2Vertex)vertices.get(name); if (nd!=null) return nd; else { Ps2Vertex vertex=new Ps2Vertex(name); vertices.put(name, vertex); return vertex; } } } // Fin