Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML serialization of enums

I have problems with serializing enum values.

Here is the code:

[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public class REQUEST
{
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string ID;

    [System.Xml.Serialization.XmlAttributeAttribute()]
    public REQUESTTypetype Type;
}

public enum REQUESTTypetype
{
    One,
    Two,
    Three,
    Four,
}

...

REQUEST request = new REQUEST();
request.ID = "1234";
request.Type = REQUESTTypetype.One;

XmlDocument doc = new XmlDocument();
MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms);
XmlSerializer xs = new XmlSerializer(typeof(REQUEST));
xs.Serialize(sw, request_group);
ms.Position = 0;
doc.Load(ms);
TestWriteXml(doc, @"C:\xml_test.xml");

The result is:

<?xml version="1.0" encoding="utf-8" ?> 
<REQUEST ID="1234" />

Why the enum is not serialized? I use .NET Framework 2.0.

Thank you.

like image 851
etarvt Avatar asked Oct 08 '10 13:10

etarvt


1 Answers

I found what was wrong. For every enum type

[System.Xml.Serialization.XmlAttributeAttribute()]
public REQUESTTypetype Type;

I got this:

[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool TypeSpecified;

And in the code I should do this:

request.Type = REQUESTTypetype.One;
request.TypeSpecified = true;

It works fine now. I should have post them in my question but I did not pay attention to these "specified" members at all. Thanks for your replies.

like image 193
etarvt Avatar answered Nov 15 '22 17:11

etarvt