2014-02-17 73 views
1

我有一個XML,如下所示。我想將其轉換爲c#對象。我嘗試了,但無法使其工作。將XML反序列化爲對象不起作用

<SLVGeoZone-array> 
    <SLVGeoZone> 
    <id>19</id> 
    <type>geozone</type> 
    <name>60_OLC_SC</name> 
    <namesPath>GeoZones/60_OLC_SC</namesPath> 
    <idsPath>1/19</idsPath> 
    <childrenCount>0</childrenCount> 
    </SLVGeoZone> 
    </SLVGeoZone-array> 

我有寫的C#示例代碼,它不工作:

[Serializable] 
public class SLVGeoZone 
{ 
    [XmlElement("id")] 
    public string id { get; set; } 

    [XmlElement("type")] 
    public string type { get; set; } 

    [XmlElement("name")] 
    public string name { get; set; } 

    [XmlElement("namespath")] 
    public string namespath { get; set; } 

    [XmlElement("idspath")] 
    public string idspath { get; set; } 

    [XmlElement("childrencount")] 
    public string childrencount { get; set; } 
} 

[Serializable] 
[XmlRoot("SLVGeoZone-array")] 
public class SLVGeoZone-array 
{ 
    [XmlArray("SLVGeoZone-array")] 
    [XmlArrayItem("SLVGeoZone", typeof(SLVGeoZone))] 
    public SLVGeoZone[] Car { get; set; } 
} 

而且形式:

XmlSerializer serializer = new XmlSerializer(typeof(CarCollection)); 
StreamReader reader = new StreamReader(path); 
cars = (CarCollection)serializer.Deserialize(reader); 
reader.Close(); 

有人建議我在做什麼錯?

+0

你是什麼意思 「不工作」?它是否會拋出異常?它是否返回空對象?那些難以形容的恐怖從老年人的維度中扭曲了出來? – Aron

回答

1
  1. SLVGeoZone-array是不是在C#有效的類名

    [Serializable()] 
    [XmlRoot("SLVGeoZone-array")] 
    public class SLVGeoZones 
    { 
        [XmlElement("SLVGeoZone")] 
        public SLVGeoZone[] Cars { get; set; } 
    } 
    
  2. XmlElement屬性值必須完全一樣,在XML文件中的元素名稱。你的不是。

    [Serializable()] 
    public class SLVGeoZone 
    { 
        [XmlElement("id")] 
        public string id { get; set; } 
    
        [XmlElement("type")] 
        public string type { get; set; } 
    
        [XmlElement("name")] 
        public string name { get; set; } 
    
        [XmlElement("namesPath")] 
        public string namespath { get; set; } 
    
        [XmlElement("idsPath")] 
        public string idspath { get; set; } 
    
        [XmlElement("childrenCount")] 
        public string childrencount { get; set; } 
    } 
    
  3. 什麼是CarCollection,爲什麼是你想反序列化XML作爲CarCollection,而不是你這裏顯示類?

    XmlSerializer serializer = new XmlSerializer(typeof(SLVGeoZones)); 
    StreamReader reader = new StreamReader("Input.txt"); 
    var items = (SLVGeoZones)serializer.Deserialize(reader); 
    reader.Close(); 
    
+0

感謝您的耐心和時間..它的工作。 – user1687824