In .NET Xml Serialization, is it possible to serialize a class with an enum property with different

Posted by Lasse V. Karlsen on Stack Overflow See other posts from Stack Overflow or by Lasse V. Karlsen
Published on 2010-05-24T21:51:18Z Indexed on 2010/05/27 22:31 UTC
Read the original article Hit count: 170

Filed under:
|
|
|

I have a class, containing a list property, where the list contains objects that has an enum property.

When I serialize this, it looks like this:

<?xml version="1.0" encoding="ibm850"?>
<test>
  <events>
    <test-event type="changing" />
    <test-event type="changed" />
  </events>
</test>

Is it possible, through attributes, or similar, to get the Xml to look like this?

<?xml version="1.0" encoding="ibm850"?>
<test>
  <events>
    <changing />
    <changed />
  </events>
</test>

Basically, use the property value of the enum as a way to determine the tag-name? Is using a class hierarchy (ie. creating subclasses instead of using the property value) the only way?

Edit: After testing, it seems even a class-hierarchy won't actually work. If there is a way to structure the classes to get the output I want, even with sub-classes, that is also an acceptable answer.

Here's a sample program that will output the above Xml (remember to hit Ctrl+F5 to run in Visual Studio, otherwise the program window will close immediately):

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

namespace ConsoleApplication18
{
    public enum TestEventTypes
    {
        [XmlEnum("changing")]
        Changing,

        [XmlEnum("changed")]
        Changed
    }
    [XmlType("test-event")]
    public class TestEvent
    {
        [XmlAttribute("type")]
        public TestEventTypes Type { get; set; }
    }
    [XmlType("test")]
    public class Test
    {
        private List<TestEvent> _Events = new List<TestEvent>();

        [XmlArray("events")]
        public List<TestEvent> Events { get { return _Events; } }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Test test = new Test();
            test.Events.Add(new TestEvent { Type = TestEventTypes.Changing });
            test.Events.Add(new TestEvent { Type = TestEventTypes.Changed });

            XmlSerializer serializer = new XmlSerializer(typeof(Test));
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            serializer.Serialize(Console.Out, test, ns);
        }
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET