Question about XmlAttribute and InvalidProgramException

Topics: graph, serialization
Jul 22, 2012 at 9:27 AM

Hi, everyone.

I am trying to serialize a undirected graph with customized vertices and edges. Here is the code:

            var graph = new UndirectedGraph<ElectricalNode, ElectricalEdge>();

            var Node0 = new ElectricalNode(0, "Node0", 10.0);
            var Node1 = new ElectricalNode(1, "Node1", 10.0);
            graph.AddVertex(Node0);
            graph.AddVertex(Node1);

            IEdge<ElectricalNode> Edge0_1 = new ElectricalEdge(0, Node0, Node1);
           
            graph.AddEdge((ElectricalEdge)Edge0_1);

            Console.WriteLine("Graph created successfully.");

            using (var xwriter = XmlWriter.Create("graph_test.xml"))
            {
                graph.SerializeToGraphML(xwriter, graph.GetVertexIdentity(), graph.GetEdgeIdentity());
                Console.WriteLine("GML created successfully.");
            }

I defined my own vertex type named ElectricalNode:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace OptimLib
{
    public struct ElectricalNode
    {
        private int ID;
        private string Name;
        private double VBase;

        public ElectricalNode(int id, string name, double vBase)
        {
            ID = id;
            Name = name;
            VBase = vBase;
        }

        [XmlAttribute("NodeName")]
        public string NodeName
        {
            get { return Name; }
        }

    }
}

and my own edge type named ElectricalEdge:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QuickGraph;

namespace OptimLib
{
    public struct ElectricalEdge : IUndirectedEdge<ElectricalNode>
    {
        private int ID;
        private ElectricalNode StartNode;
        private ElectricalNode EndNode;

        public ElectricalEdge(int id, ElectricalNode startNode, ElectricalNode endNode) {
            ID = id;
            StartNode = startNode;
            EndNode = endNode;
        }

        ElectricalNode IEdge<ElectricalNode>.Source
        {
            get { return StartNode; }
        }

        ElectricalNode IEdge<ElectricalNode>.Target
        {
            get { return EndNode; }
        }
    }
}

It is said that QuickGraph can serialize custom attributes with [XmlAttribute(...)], I think my code has this sentence. However, an InvalidProgramException always happens when I run the program, while the error disappeared if I delete the [XmlAttribute(...)] in the ElectricalNode class.

Anyone can solve the problem? Many thanks in advance!