在DotNet XmlSerializer中将XML元素名称序列化为枚举

时间:2018-12-26 12:14:25

标签: .net xml-serialization

是否可以通过属性(或其他方式)说服.NET XmlSerializer将类的枚举反序列化为表示它的元素的名称,反之亦然?

示例:

<root>
                <a>4</a>
                <b>5</b>
                <c>6</c>
</root>

[Serializable]
public enum NameEnum { a,b,c }

[Serializable]
public class Class {
                public NameEnum Name {get;set;}
                public int Value {get;set;}
}

1 个答案:

答案 0 :(得分:0)

您应该能够做到这一点:

using System.Xml.Serialization;


[Serializable]
public enum NameEnum
{
    [XmlEnum(Name = "a")]
    a,
    [XmlEnum(Name = "b")]
    b,
    [XmlEnum(Name = "c")]
    c
}

工作示例,添加到控制台应用程序:

class Program
    {
        static void Main(string[] args)
        {
            AClass c = new AClass();
            c.Name = NameEnum.c;
            c.Value = 2;

            using (MemoryStream ms = new MemoryStream())
            {
                XmlSerializer s = new XmlSerializer(typeof(AClass));
                s.Serialize(ms, c);
                File.WriteAllBytes(@"c:\test\serializeEnum.xml", ms.ToArray());

            }

            using (MemoryStream ms2 = new MemoryStream(File.ReadAllBytes(@"c:\test\serializeEnum.xml")))
            {
                XmlSerializer xs = new XmlSerializer(typeof(AClass));
                AClass t = (AClass)xs.Deserialize(ms2);
                Console.WriteLine(t.Name.ToString());
                Console.WriteLine(t.Value.ToString());
                Console.ReadLine();
            }


        }
    }

    [Serializable]
    public enum NameEnum
    {
        [XmlEnum(Name = "a")]
        a,
        [XmlEnum(Name = "b")]
        b,
        [XmlEnum(Name = "c")]
        c
    }

    [Serializable]
    public class AClass
    {
        public NameEnum Name { get; set; }
        public int Value { get; set; }
    }