Change the order of elements when serializing XML

前端 未结 2 435
我寻月下人不归
我寻月下人不归 2020-12-06 08:58

I need to serialize an Object to XML and back. The XML is fix and I can\'t change it. I fail to generate this structure after bookingList.

How can I \"

相关标签:
2条回答
  • 2020-12-06 09:43

    Try decorating the properties of the bookingListclass with the XmlElementAttribute, in order to control how the objects of that class are going to be serialized to XML.

    Here's an example:

    public class bookingList
    {
        [XmlElement(Order = 1)]
        public string error { get; set; }
        [XmlElement(Order = 2)]
        public int counter { get; set; }
        [XmlElement(ElementName = "booking", Order = 3)]
        public List<booking> bookings = new List<booking>();
    }
    
    public class booking
    {
        public int id { get; set; }
    }
    

    In my test I obtained this output:

    <?xml version="1.0" ?> 
    <bookingList>
        <error>sample</error>
        <counter>0</counter>
        <booking>
            <id>1</id> 
        </booking>
        <booking>
            <id>2</id> 
        </booking>
        <booking>
            <id>3</id> 
        </booking> 
    </bookingList>
    

    Related resources:

    • Controlling XML Serialization Using Attributes
    0 讨论(0)
  • 2020-12-06 09:53

    I was facing with this problem and i solved it... Well it is very interesting, and this is a bug in .net maybe.

    the problem is here: public List<booking> booking= new List<booking>();

    You should use: public List<booking> booking { get; set; }

    And you will get the defined order .... but why? who knows... :)

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