I have a class containing a list property in which the list contains objects that have the 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 the like, to make Xml look like this?
<?xml version="1.0" encoding="ibm850"?>
<test>
<events>
<changing />
<changed />
</events>
</test>
Basically, use the value of an enumeration property as a way to determine the tag name? Is using a class hierarchy (i.e., subclassing instead of using a property value) the only way?
Change . After testing, it seems that even the class hierarchy does not actually work. If there is a way to structure classes to get the result I want, even with subclasses, this is also an acceptable answer.
, Xml ( Ctrl + F5 Visual Studio, ):
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);
}
}
}