2011-06-23 85 views
17

我需要將對象序列化爲XML並返回。 XML已修復,我無法更改它。 bookingList之後,我無法生成此結構。在序列化XML時更改元素的順序

我怎樣才能「團」這些<booking>元素出現作爲一個列表,並保持<error> & <counter>名單<booking>元素之前。

見我的例子在這裏:

結構,我需要....

<nicexml> 
<key_id>1234567</key_id> 
<surname>Jil</surname> 
<name>Sander</name> 
<station_id>1</station_id> 
<ownBookings> 
    <bookingList> 
     <error></error> 
     <counter>20</counter> 
     <booking> 
      <bookingID>1234567890</bookingID> 
     </booking> 
     <booking> 
      <bookingID>2345678901</bookingID> 
     </booking> 
    </bookingList> 
</ownBookings> 
</nicexml> 

結構我下面的C#代碼得到....

<nicexml> 
<key_id>1234567</key_id> 
<surname>Jil</surname> 
<name>Sander</name> 
<station_id>1</station_id> 
<ownBookings> 
    <bookingList> 
      <booking> 
     <booking> 
      <bookingID>1234567890</bookingID> 
     </booking> 
     <booking> 
      <bookingID>2345678901</bookingID> 
     </booking> 
      <booking> 
     <error></error> 
     <counter>20</counter> 
    </bookingList> 
</ownBookings> 
</nicexml> 

C#代碼:

using System; 
using System.Xml.Serialization; 
using System.Collections.Generic; 

namespace xml_objects_serials 
{ 
    public class bookings 
    { 
     public class nicexml 
     { 
      public string key_id 
      { get; set; } 

      public string surname 
      { get; set; } 

      public string name 
      { get; set; } 

      public int station_id 
      { get; set; } 

      public ownBookings ownBookings 
      { get; set; } 

     } 

     public class ownBookings 
     { 
      public bookingList bookingList 
      { get; set; } 

     } 
     public class bookingList { 
      public string error 
      { get; set; } 
      public int counter 
      { get; set; } 
      public List<booking> booking= new List<booking>(); 
     } 

     public class booking 
     { 
      public int bookingID 
      { get; set; } 
     } 
    } 

回答

25

嘗試裝飾親將bookingList類與XmlElementAttribute相關聯,以便控制如何將該類的對象序列化爲XML

下面是一個例子:

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; } 
} 

在我的測試我得到這樣的輸出:

<?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> 

相關資源:

+0

thx ...元素順序...爲什麼我沒有得到這從msdn ....謝謝你 –

+0

我不知道這個「elementorder」。萬分感謝! –

-3

我正面臨着這個問題,我解決了它......這是非常有趣的,這是一個錯誤.net也許。

的問題是在這裏: public List<booking> booking= new List<booking>();

你應該使用: public List<booking> booking { get; set; }

,你會得到定義的順序....但是爲什麼呢?誰知道... :)