How to rename XML attribute that generated after serializing List of objects

后端 未结 4 1149
我寻月下人不归
我寻月下人不归 2020-12-01 12:24

I am serializing List of objects List , and XmlSerializer generates attribute, I want rename it or rem

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 12:45

    The most reliable way is to declare an outermost DTO class:

    [XmlRoot("myOuterElement")]
    public class MyOuterMessage {
        [XmlElement("item")]
        public List Items {get;set;}
    }
    

    and serialize that (i.e. put your list into another object).


    You can avoid a wrapper class, but I wouldn't:

    class Program
    {
        static void Main()
        {
            XmlSerializer ser = new XmlSerializer(typeof(List),
                 new XmlRootAttribute("Flibble"));
            List foos = new List {
                new Foo {Bar = "abc"},
                new Foo {Bar = "def"}
            };
            ser.Serialize(Console.Out, foos);
        }
    }
    
    public class Foo
    {
        public string Bar { get; set; }
    }
    

    The problem with this is that when you use custom attributes you need to be very careful to store and re-use the serializer, otherwise you get lots of dynamic assemblies loaded into memory. This is avoided if you just use the XmlSerializer(Type) constructor, as it caches this internally automatically.

提交回复
热议问题