2014-06-18 53 views
0

在下面的組合中,請注意序列化屬性是小寫字母,並且根中的數組屬性相應序列化,但其子元素不符合此裝飾。具有數組屬性的對象的Xml序列化

我spected這樣的:

<engine> 
    <servos> 
    <servo> 
    </servo> 
    </servos> 
</engine> 

而是我得到這個:

<engine> 
    <servos> 
    <Servo> <!-- here is the problem--> 
    </Servo> 
    </servos> 
</engine> 

代碼:

[XmlRoot("engine")] 
    public class Engine { 

    [XmlArray("servos")] 
    public List<Servo> Servos { 
     get { return servos; } 
     set { servos = value; } 
     } 
    } 

    [XmlRoot("servo")] //Child ignoring lowercase decoration 
    public class Servo { 
    } 

什麼是序列化的屬性指示正確的方法是什麼?

+0

的[XmlRoot()FOR XML Serilization不工作(可能重複http://stackoverflow.com/questions/1440845/xmlroot- for-xml-serilization-does-not-work) – toATwork

回答

0

你必須XmlArrayItem屬性添加到Servos屬性:

[XmlArrayItem("servo")] 
[XmlArray("servos")] 
public List<Servo> Servos { 
    get; 
    set ; 
    } 
} 
+0

儘管@toATwork指出的答案有效,但我更喜歡這樣,因爲在這種情況下,XmlArrayItem屬性的意圖比XmlType更明確。 –