我在使用 Boost Graph Library 读取 GraphML 文件时遇到问题。该文件创建时没有问题,但读回它会引发解析错误。这是我正在做的事情的总结:
我创建了图表示例,并使用
write_graphml
保存它。该图只有唯一的“顶点”属性,没有“边”属性。用于执行此操作的代码是:
... variables ...
typedef boost::property<boost::vertex_name_t, std::string> Node_name;
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, Node_name> Graph;
typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;
typedef std::unordered_map<std::string, Vertex> VertexMap;
Graph g;
VertexMap vertex_map;
... build the graph ...
std::string name = "../tmp/" + analyzed_file + ".graphml";
std::ofstream graph_ML(name);
boost::dynamic_properties dp;
dp.property("name", boost::get(boost::vertex_name, g));
boost::write_graphml(graph_ML, g, dp);
这段代码完美运行。我的文件已正确保存在所需的目录中。
但是,当我尝试使用以下代码读取它时:
std::string graph_ml_file_name = "../tmp/" + analyzed_file + ".graphml";
std::ifstream graphml_file(graph_ml_file_name);
if(!graphml_file)
{
std::cerr << "Error opening the file" << std::endl;
return -1;
}
boost::dynamic_properties dp;
dp.property("name", boost::get(boost::vertex_name, g));
try
{
boost::read_graphml(graphml_file,g,dp);
}
catch(const std::exception& e)
{
std::cerr << "Error opening the graphml file" << e.what() << std::endl;
return -1;
}
我收到错误:打开 graphml 文件时出错:解析错误:无法识别的类型“
我浏览了文档,但找不到有关处理此错误的具体信息。有没有人遇到过这个问题或者可以建议可能出了什么问题?
我一直在网上研究类似的错误以及阅读官方的Boost Graph文档,但我还没有找到解决方案。
鉴于问题中的信息,无法在我的系统上重现此问题。
这是我的测试程序,也许您可以发现差异或发布编辑后的版本,确实重现您的问题:
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graphml.hpp>
#include <boost/graph/random.hpp>
#include <filesystem>
#include <fstream>
#include <random>
#include <unordered_map>
using Node_name = boost::property<boost::vertex_name_t, std::string>;
using Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, Node_name>;
using Vertex = boost::graph_traits<Graph>::vertex_descriptor;
using VertexMap = std::unordered_map<std::string, Vertex>;
auto analyze(std::string name) {
Graph g;
std::mt19937 prng(std::random_device{}());
boost::generate_random_graph(g, 10, 20, prng);
VertexMap vertex_map;
for (auto vd : boost::make_iterator_range(vertices(g))) {
auto n = name + std::to_string(vd);
put(boost::vertex_name, g, vd, name);
vertex_map.emplace(n, vd);
}
auto fname = std::filesystem::temp_directory_path() / (name + ".graphml");
std::ofstream graph_ML(fname);
boost::dynamic_properties dp;
dp.property("name", get(boost::vertex_name, g));
write_graphml(graph_ML, g, dp);
return fname;
}
void reload(std::filesystem::path fname) {
std::ifstream graphml_file(fname);
boost::dynamic_properties dp;
Graph g;
dp.property("name", get(boost::vertex_name, g));
read_graphml(graphml_file, g, dp);
}
int main() {
auto fname = analyze("so-test");
std::cout << "Written to " << fname << "\n";
reload(fname);
}
一些演示运行: