Search code examples
serializationquickgraph

How to serialize additional edge information in QuickGraph?


I'm working with a graph dataset that could have edges of different logical meaning, like that:

"Bavaria" -[PART_OF]-> "Germany"
"Germany" -[NEIGHBOR_OF]-> "France"

I represent this domain by using the QuickGraph.TaggedEdge where TTag generic parameter is a string:

QuickGraph.BidirectionalGraph<IGeographicalUnit, TaggedEdge<IGeographicalUnit, string>>

This works perfectly until the moment I try to serialize my graph to .graphml form:

using (var w = XmlWriter.Create(@"C:\Temp\data.graphml"))
{
    _graph.SerializeToGraphML<IGeographicalUnit, TaggedEdge<IGeographicalUnit, string>, BidirectionalGraph<IGeographicalUnit, TaggedEdge<IGeographicalUnit, string>>>(w);
}

Serialized edge data doesn't contain any tag information, only source and target:

<edge id="0" source="0" target="1" />

What I want is something like:

<edge id="0" source="0" target="1" tag="PART_OF" />

So, the question is, how can I enforce this tag to be serialized?


Solution

  • To solve this problem, I created my own edge implementation pretty similar to the TaggedEdge mentioned above:

    public class DataEdge<TVertex> : Edge<TVertex>
    {
        [XmlAttribute("Tag")]
        public string Tag { get; set; }
    
        public DataEdge(TVertex source, TVertex target)
            : base(source, target) { }
    
        public DataEdge(TVertex source, TVertex target, string tag)
            : this(source, target)
        {
            Tag = tag;
        }
    }
    

    Then I replaced TaggedEdge occurrences with my DataEdge. After that, serialization produced the following XML output:

    <edge id="0" source="0" target="1">
      <data key="Tag">PART_OF</data>
    </edge>
    

    The problem is solved, but I hope that another solution exists that don't involve writing your own Edge implementations.