Link to home
Start Free TrialLog in
Avatar of tommym121
tommym121Flag for Canada

asked on

C# - XML serialization of an ENUM

i have an enum like this

    enum Importance
    {
      None=0,
      Trivial=1,
      Regular=2,
      Important=3,
      Critica=4
    };

I will like to XML serialize it and be able to read from a file . So I can add and modify the enum out side the application.  How will I specify the XML attributes in the enum, and what function(s) I need to call to retrival enum form file?
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
there's no problem serializing enum properties as xml attribute, simply decorate the property with  [XmlAttribute]:
    public class Test
    {
        public enum Importance
        {
            None = 0,
            Trivial = 1,
            Regular = 2,
            Important = 3,
            Critica = 4
        };
 [XmlAttribute]
        public Importance importance { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            StringBuilder sb = new StringBuilder();
            using (var writer = XmlWriter.Create(sb))
            {
                var test = new Test
                {
                    importance = Test.Importance.Regular
                };
                var serializer = new XmlSerializer(test.GetType());
                serializer.Serialize(writer, test);
            }
            Console.WriteLine(sb.ToString());
        }
    }

Open in new window