diff --git a/lib/graph/graph_xml.hpp b/lib/graph/graph_xml.hpp new file mode 100644 index 0000000..25af7a0 --- /dev/null +++ b/lib/graph/graph_xml.hpp @@ -0,0 +1,74 @@ +#include + +#include +#include + +#include +#include + +namespace { + +template +void readVertices(Graph& g, F vertexCreator, const xmlNodePtr root_element) +{ + for (xmlNodePtr cur_node = root_element->children; cur_node; cur_node = cur_node->next) + if (cur_node->type == XML_ELEMENT_NODE) { + + const std::string vertex( reinterpret_cast(cur_node->properties->children->content)); + V v = vertexCreator(vertex); + + std::vector edges; + for (xmlNodePtr cur_kid = cur_node->children; cur_kid; cur_kid = cur_kid->next) + if (cur_kid->type == XML_ELEMENT_NODE && cur_kid->children->type == XML_TEXT_NODE) { + const std::string e( reinterpret_cast(cur_kid->children->content)); + edges.push_back(vertexCreator(e)); + } + + g.setEdges(v, edges); + } +} + +} // anonym namespace + +template +Graph readGraphFromXML(const std::string& filename, F vertexCreator) +{ + xmlDocPtr doc = xmlReadFile(filename.c_str(), NULL, 0); + if (doc == NULL) + throw std::runtime_error("Failed to parse " + filename); + + xmlNodePtr root_element = NULL; + root_element = xmlDocGetRootElement(doc); + + Graph g; + readVertices(g, vertexCreator, root_element); + + xmlFreeDoc(doc); + xmlCleanupParser(); + return g; +} + +template +void writeGraphToXML(const Graph& g, const std::string& filename, F vertexSerializer) +{ + std::ofstream file; + file.open (filename); + if (!file.is_open()) + throw std::runtime_error("Failed to open " + filename + " to write."); + + file << "" << std::endl; + file << "" << std::endl; + + for (const auto cit : g) { + const std::string v = vertexSerializer(cit); + file << "" << std::endl; + for (const auto cit2 : g.neighboursOf(cit)) { + const std::string n = vertexSerializer(cit2); + file << " " << v << "" << std::endl; + } + file << "" << std::endl; + } + + file << "" << std::endl; + file.close(); +}