-
-
Notifications
You must be signed in to change notification settings - Fork 71
Xml Serialization
QuikGraph supports loading and saving graphs to and from Xml. The implementation builds on top of XmlReader
and XmlWriter
and is located in the SerializationExtensions
class from the QuickGraph.Serialization
module.
To serialize a graph, call the SerializeToXml
extension methods with an XmlWriter
instance and delegates that can map vertices and edges to an identifier string. The serialization method also supports custom delegate to write additional information per vertex, edge.
class MyVertex
{
public int ID { get; set; }
}
class MyEdge : IEdge<MyVertex>
{
string Name { get; set; }
string Tag { get; set; }
}
var graph = new AdjacencyGraph<MyVertex, MyEdge>();
...
using (var writer = XmlWriter.Create(...))
{
graph.SerializeToXml(
writer,
v => v.ID, // Let's use ID as the vertex ID
AlgorithmExtensions.GetEdgeIdentity(graph), // Let QuikGraph give an id to edges
"graph", "myvertex", "myedge", "" // names of the graph, vertex, edge, node xml tags and the namespace uri
);
}
To deserialize a graph, call the DeserializeFromXml
extension methods with an XmlReader
or an IXPathNavigable
instance. The result of the method will be the deserialized graph instance.
using (var reader = XmlReader.Create(...))
{
AdjacencyGraph<string, Edge<string>> graph = reader.DeserializeFromXml(
"graph", "myvertex", "myedge", "", // names of the graph, vertex, edge, node xml tags and the namespace uri
_ => new AdjacencyGraph<string, Edge<string>>(),
r => r.GetAttribute("id"),
r => new Edge<string>(
r.GetAttribute("source") ?? throw new ArgumentException("Must have source attribute"),
r.GetAttribute("target") ?? throw new ArgumentException("Must have target attribute")));
...
}
The serializer supports the delegates to write additional information of the vertex, edge and graph types.