在使用Boost Graph读取GraphML文件时使用vertex_name

Using vertex_name when reading a GraphML file with Boost Graph

本文关键字:vertex name 文件 读取 Boost Graph GraphML      更新时间:2023-10-16

我正在尝试加载一个简单的GraphML文件,这样每个顶点都有一个顶点名称存储在GraphML中。我可以更改GraphML,重要的是,我可以访问vertex_name之后的代码。

下面是我可以提取的仍然显示问题的最小示例:

#include <iostream>
#include <string>
#include <fstream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graphml.hpp>
int main()
{
    using namespace boost;
    typedef adjacency_list<vecS, vecS, directedS,property<vertex_name_t,std::string> > BoostGraphType;
    typedef dynamic_properties BoostDynamicProperties;
    std::string fn = "simple.graphml";
    std::ifstream is(fn.c_str()); 
    if (!is.is_open())
    {
        std::cout << "loading file '" << fn << "'failed." << std::endl;
        throw "Could not load file.";
    }
    BoostGraphType g;
    BoostDynamicProperties dp ;
    const std::string vn = "vertex_name";
    dp.property(vn,get(vertex_name,g));
    read_graphml(is, g, dp);
    for (auto vp = vertices(g); vp.first != vp.second; ++vp.first)
    {
        std::cout << "index '" << get(vertex_index,g,*vp.first) << "' ";
        std::cout << "name '" << get(vertex_name,g,*vp.first) << "'"
        << std::endl;
    }
    return 0;
}

我使用以下GraphML测试文件:

<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
    http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
  <key id="d0" for="node" attr.name="vertex_name" attr.type="string"/>
  <graph id="G" edgedefault="directed">
    <node id="A"> <data key="d0">A</data> </node>
    <node id="B"> <data key="d0">B</data> </node>
    <edge id="0" source="A" target="B"/>
   </graph>
</graphml>

read_graphml抛出异常,并提供有用的消息(e.what()):

 parse error: unrecognized type "   

似乎这个问题与vertex_name关联有关(我从对我之前问题的评论中得到的)。

如果我删除

<data key="d0">A</data>

,它可以工作。

但是,我需要能够通过vertex_name来识别顶点。

我怎么能解决这个问题,使它正确解析graphml和不抛出?我做错了什么?

你的代码运行起来很完美

>wilbert.exe
index '0' name 'A'
index '1' name 'B'