// Read a Graph from XML File import java.io.*; import java.net.*; import java.util.*; import mit16_410_13.*; class Ps3XMLGraph { Hashtable vertices; Ps3XMLGraph () { vertices = new Hashtable(); } public Dictionary readGraph (String path) { XMLStream strm; FileInputStream istrm=null; try { Ps3Vertex 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) { System.out.println("VERTEX not in a GRAPH"); ingraph=true; // recover } double x=new Double(atag.getAttribute("x")).doubleValue(); double y=new Double(atag.getAttribute("y")).doubleValue(); currentVertex=findVertexCreate(atag.getAttribute("name")); currentVertex.setXlocation(x); currentVertex.setYlocation(y); } 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 { Ps3Vertex tovertex=findVertexCreate(atag.getAttribute("vertex")); double len=new Double(atag.getAttribute("length")).doubleValue(); currentVertex.addEdge(new Ps3Edge(tovertex, len)); } } 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; } Ps3Vertex findVertexCreate (String name) { Ps3Vertex nd=(Ps3Vertex)vertices.get(name); if (nd!=null) return nd; else { Ps3Vertex vertex=new Ps3Vertex(name); vertices.put(name, vertex); return vertex; } } } // Fin