#ifndef PERSISTENTGRAPH_H #define PERSISTENTGRAPH_H ///////////////////////////////////////////////////////////////////// // persistentGraph.cpp - convert graph to/from XML file // // ver 2 // // Language: C++, Visual Studio, 2010, SP1 // // Platform: Toshiba Portege R705, Windows 7, SP1 // // Application: Summer Projects // // Author: Jim Fawcett, Syracuse University, CST 4-187 // // www.lcs.syr.edu/faculty/fawcett, (315) 443-3948 // ///////////////////////////////////////////////////////////////////// /* * Package Operations: * ------------------- * This package uses XmlReader, XmlWriter, and graph packages to retrieve * graph from and persist to an XML string. This, of course, supports * retrieving from and persisting to files with a little added file reading * and writing supplied by the user. * * Required Files: * --------------- * persistentGraph.h, persistentGraph,cpp, graph.h, graph.cpp, * XmlReader.h, XmlReader.cpp * * Build Process: * -------------- * cl /EHa persistentGraph.cpp graph.cpp XmlReader.cpp * * Maintenance History: * -------------------- * ver 2 : 01 Jul 11 * - added capability to save XML file after changes * - restructured into global functions and test stub * ver 1 : 30 Jun 11 * - first release * */ #include #include "..\graph\graph.h" #include "..\..\XmlReader\XmlReader\XmlReader.h" #include "..\..\XmlWriter\XmlWriter\XmlWriter.h" //----< create graph from an XML string >---------------------------- template void graphFromXML(graph& gr, const std::string& xml) { XmlReader rdr(xml); while(rdr.next()) { std::string tag = rdr.tag(); if(tag == "name") { gr.name() = rdr.body(); } else if(tag == "vertex") { vertex* pV = new vertex; XmlReader::attribElems attribs = rdr.attributes(); if(attribs.size() > 0) { pV->value() = attribs[0].second; gr.addVertex(pV); } } else if(tag == "edge") { edg e; XmlReader::attribElems attribs = rdr.attributes(); if(attribs.size() > 0) { e.value() = attribs[0].second; } if(attribs.size() > 2) { vertex* pVfrom = gr.findVertex(attribs[1].second); vertex* pVto = gr.findVertex(attribs[2].second); if(pVfrom != 0 && pVto != 0) gr.addEdge(attribs[0].second,pVfrom,pVto); } } } } //----< persist graph to XML string >-------------------------------- template std::string graphToXML(graph& gr) { std::string xml; XmlWriter wrtr; wrtr.addDeclaration(); wrtr.start("graph"); XmlWriter bodyWrtr; bodyWrtr.start("name"); bodyWrtr.addBody(gr.name()); bodyWrtr.end(); for(size_t i=0; ivalue()); } for(size_t i=0; i* pV = gr[i]; for(size_t j=0; jsize(); ++j) { bodyWrtr.start("edge /"); bodyWrtr.addAttribute("name",(*pV)[j].value()); bodyWrtr.addAttribute("from",pV->value()); bodyWrtr.addAttribute("to",(*pV)[j].pVertex()->value()); } } wrtr.addBody(bodyWrtr.xml()); wrtr.end(); return wrtr.xml(); } #endif