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

后端 未结 4 1048
我寻月下人不归
我寻月下人不归 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:31

    Create another class like :

           [XmlRoot("TestObjects")]
           public class TestObjects: List<TestObject>
           {
    
           }
    

    Then apply below code while sealizing :

                XmlSerializer serializer = new XmlSerializer(typeof(TestObjects));
                MemoryStream memStream = new MemoryStream();
                serializer.Serialize(memStream, tmpList);
    
    0 讨论(0)
  • 2020-12-01 12:37

    You can add an additional parameter to the XmlSerializer constructor to essentially name the root element.

    XmlSerializer xsSubmit = new XmlSerializer(typeof(List<DropDownOption>), new XmlRootAttribute("DropDownOptions"));
    

    This would result in the following structure:

    <DropDownOptions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
        <DropDownOption>
          <ID>1</ID>
          <Description>foo</Description>
        </DropDownOption>
        <DropDownOption>
          <ID>2</ID>
          <Description>bar</Description>
        </DropDownOption>
    </DropDownOptions>
    
    0 讨论(0)
  • 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<TestObject> 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<Foo>),
                 new XmlRootAttribute("Flibble"));
            List<Foo> foos = new List<Foo> {
                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.

    0 讨论(0)
  • 2020-12-01 12:47

    Change the following line from:

    XmlSerializer serializer = new XmlSerializer(typeof(List<TestObject>));
    

    To:

    XmlRootAttribute root = new XmlRootAttribute("TestObjects");     
    
    XmlSerializer serializer = new XmlSerializer(typeof(List<TestObject>), root);
    

    It should work.

    0 讨论(0)
提交回复
热议问题