Skip to content

GraphML Serialization

Alexandre Rabérin edited this page Jun 11, 2021 · 2 revisions

GraphML Serialization

GraphML is a comprehensive and easy-to-use file format for graphs. QuikGraph supports loading and saving directed graphs to this format. The GraphML serialization APIs are exposed through the GraphMLExtensions extension methods (in QuikGraph.Serialization).

The serialization code uses dynamic code generation to provide high performance in reading and writing custom properties.

Serializing graphs

To serialize a graph, simply calls the SerializeToGraphML extension methods with an XmlWriter instance.

var graph = new AdjacencyGraph<int, Edge<int>>();
...
using (var xmlWriter = XmlWriter.Create(...))
{
    graph.SerializeToGraphML(xmlWriter);
}

Deserializing graphs

To deserialize a graph, creates the graph instance and calls the DeserializeFromGraphML.

var graph = new AdjacencyGraph<int, Edge<int>>();
using (var xmlReader = XmlReader.Create(...))
{
     graph.DeserializeFromGraphML(
         xmlReader,
         id => int.Parse(id),
         (source, target, id) => new Edge<int>(source, target));
}

Serializing Custom Fields

Attributes

The serializer supports the XmlAttributeAttribute attribute on public properties of the vertex, edge and graph types. These properties will be declared and serialized in the GraphML stream. The supported property types are bool, int, long, float, double and string.

class IntEdge : Edge<int>
{
    ...
    [XmlAttribute("name")]
    public string Name { get; set; }
}

Default values can also be specified for the properties by using the DefaultValueAttribute attribute.

...
[XmlAttribute("name")]
[DefaultValue("unknown")]
public string Name { get; set; }

Custom identifiers

By default serialization to GraphML uses the AlgorithmExtensions.GetVertexIdentity(g) and AlgorithmExtensions.GetEdgeIdentity(g) to create identifiants respectively for vertices and edges for a given graph.

Note that this default behavior can be customized by using the serialization method that allows to specify both vertex and edge identities. This will allow you to generate a GraphML with custom id. Note also that this is true for the deserialization which will help you creating graph object based on them. Below is an example of serialization using custom id for vertices.

// NOTE: Node is a class having X and Y values.
// NOTE 2: Edge is an Edge<Node>
var graph = new BidirectionalGraph<Node, Edge>();
var node1 = new Node(1, 2);
var node2 = new Node(1, 3);
graph.AddVertex(node1);
graph.AddVertex(node2);
graph.AddEdge(new Edge(node1, node2));

// ...
// Serialization with custom vertex identifier and default edge identifier
graph.SerializeToGraphML(
    writer,
    vertex => $"vertex({vertex.X},{vertex.Y})", // <=
    graph.GetEdgeIdentity());

This will produce a GraphML with vertices written like this:

<node id="vertex(1,2)"> <data key="X">1</data> <data key="Y">2</data> </node>

Clone this wiki locally