Question

I have a class that has a property with data type DayOfWeek, I need to serialize it into XML, when I'm serializing it the DayOfWeek is serialized by its name, like 'Monday' and etc. I need it's related value Here is my Class:

public class myClass
{
 [XmlAttribute("DayOfWeek")]
 public DayOfWeek myDay;
}

This is the Serialized string:

<myClass DayOfWeek="Monday" />
<myClass DayOfWeek="Friday" />

my desire format should be something like this:

   <myClass DayOfWeek="1" />
   <myClass DayOfWeek="5" />

I cannot use get and set. I think that there should be an attribute for doing that. Thank you for your help. :)

here is my serializer method

 public static SqlXml Serialize<T>(T dataObject, string defaultNamespace = DefaultNamespace)
        {
            var xmlSerializer = new XmlSerializer(typeof(T), defaultNamespace);
            var wr = new StringWriter();
            var settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true, Encoding = Encoding.UTF8 };

            using (var responseWriter = XmlWriter.Create(wr, settings))
            {
                if (responseWriter != null)
                    xmlSerializer.Serialize(responseWriter, dataObject);
            }
            using (var xmlReader = XmlReader.Create(new StringReader(wr.ToString())))
            {
                return new SqlXml(xmlReader);
            }
        }

this method is working without any issue.

Was it helpful?

Solution 2

Ok .... this is my final ( and not the best) solution!

I just created another enum ...

[Serializable]
public enum DayOfWeekEnum
{
    [EnumMember]
    [XmlEnum(Name = "0")]
    Sunday = 0,

    [EnumMember]
    [XmlEnum(Name = "1")]
    Monday = 1,

    [EnumMember]
    [XmlEnum(Name = "2")]
    Tuesday = 2,

    [EnumMember]
    [XmlEnum(Name = "3")]
    Wednesday = 3,

    [EnumMember]
    [XmlEnum(Name = "4")]
    Thursday = 4,

    [EnumMember]
    [XmlEnum(Name = "5")]
    Friday = 5,

    [EnumMember]
    [XmlEnum(Name = "6")]
    Saturday = 6,
}

OTHER TIPS

Use

[XmlIgnore]

And then create a property that returns its int value. (Though I'll be happy to find out there's a better built-in way.)

For more information see How do I serialize an enum value as an int? .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top