Reputation: 321
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.
Upvotes: 9
Views: 19134
Reputation: 321
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.
Upvotes: 17
Reputation: 1063298
In your actual code, is the member:
?
All 3 must be true. For nested types, every parent type in the nesting must be public.
Additional things that would exclude it:
Upvotes: 0
Reputation: 11564
Do you see the same problem when you set the type to "Two" or "Three"? Is it because "One" is the default value and so can be assumed? It might be some artifact of loading this into an XmlDocument and then saving it with your code that you've not shown (TestWriteXml).
This slightly modified version of your code (I'm writing to a StringBuilder and then ToString'ing it at the end)...
REQUEST request = new REQUEST();
request.ID = "1234";
request.Type = REQUESTTypetype.One;
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
XmlSerializer xs = new XmlSerializer(typeof(REQUEST));
xs.Serialize(sw, request);
Console.WriteLine(sb.ToString());
... using the EXACT same types as you mention above appears to work fine. I get this at the console...
<?xml version="1.0" encoding="utf-16"?>
<REQUEST xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http:/
/www.w3.org/2001/XMLSchema" ID="1234" Type="One" />
I didn't change the definition of REQUEST or the enum REQUESTTypetype.
Upvotes: 2