I am trying to read a graphml file using the BGL library. I can successfully read the file and gathers the properties linked to each node.
However the node entries in my graphml file also have a non trivial id I would like to retrieve. The best would be to be able to use this string id as a node index, but that may not be achievable due to the fact that would put a constraint on the VertexList further than being a container. So, at the very least, I would like the id information to be preserved and to be able to access it. When writing the graph immediately after, the node ids are replaced by "n0", "n1",... which hints me towards thinking that boost doesn't keep the node id information. Is that really so? Did I miss something?
Below is the code I use:
struct VertexProperty
{
std::string name ;
};
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, VertexProperty, boost::no_property> Graph;
int main(){
std::ifstream inFile;
inFile.open("in.graphml", std::ifstream::in);
if(!inFile.good()){
std::cout << "could not open file" << std::endl;
return 1;
}
Graph g;
boost::dynamic_properties dp(boost::ignore_other_properties);
dp.property("name", boost::get(&VertexProperty::name, g));
boost::read_graphml(inFile, g, dp);
std::cout << boost::num_vertices(g) << std::endl;
std::cout << g[0].name << std::endl; // I can access the node indexed by 0 properties like this
std::cout << get(&VertexProperty::name, g, 0) << std::endl; // I can retrieve a property value like that as well
std::cout << get(boost::vertex_index, g, 0) << std::endl; // doesn't give me the node id unfortunately
std::ofstream out("out.graphml", std::ofstream::out);
boost::write_graphml(out, g, dp);
return 0;
}
Ok I found a simple enough solution: modify the graphml.cc code, and treat the nodes' id as a property. Which means:
run
:
m_keys["id"] = node_key;
m_key_type["id"] = "string";
m_key_name["id"] = "id";
handle_vertex
handle_node_property("id", v, v);