Note that there are some explanatory texts on larger screens.

plurals
  1. POIn .NET Xml Serialization, is it possible to serialize a class with an enum property with different tags based on property value?
    primarykey
    data
    text
    <p>I have a class, containing a list property, where the list contains objects that has an enum property.</p> <p>When I serialize this, it looks like this:</p> <pre><code>&lt;?xml version="1.0" encoding="ibm850"?&gt; &lt;test&gt; &lt;events&gt; &lt;test-event type="changing" /&gt; &lt;test-event type="changed" /&gt; &lt;/events&gt; &lt;/test&gt; </code></pre> <p>Is it possible, through attributes, or similar, to get the Xml to look like this?</p> <pre><code>&lt;?xml version="1.0" encoding="ibm850"?&gt; &lt;test&gt; &lt;events&gt; &lt;changing /&gt; &lt;changed /&gt; &lt;/events&gt; &lt;/test&gt; </code></pre> <p>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?</p> <p><strong>Edit</strong>: 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.</p> <p>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):</p> <pre><code>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&lt;TestEvent&gt; _Events = new List&lt;TestEvent&gt;(); [XmlArray("events")] public List&lt;TestEvent&gt; 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); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload