2014-02-07 20 views
0

所有反序列化的作品除了列表:將xml解壓縮到C#列表爲空?

(resdes是一個列表)

public class SearchResponse 
{ 
    // ELEMENTS 
    [XmlElement("ResDes")] 
    public ResDes resdes { get; set; } 

    [XmlElement("Return")] 
    public Return returns { get; set; } 

    // CONSTRUCTOR 
    public SearchResponse() 
    {} 
} 

這個工程:

<Return> 
    <test>0010000725</test> 
    </Return> 


    public class Return 
{ 

    // ELEMENTS 
    [XmlElement("test")] 
    public Test test{ get; set; } 

} 

,但項目的列表還不行deserailizes成空

<ResDes > 
<item> 
    <PoBox />  
    <City1>South Korea</City1>  
    <Country>SK</Country>  
</item> 
</ResDes > 


public class ResDes 
{ 
    // ELEMENTS 
    [XmlArrayItem("item")] 
    public List<ResDesItem> ResDesItem { get; set; } 

    // CONSTRUCTOR 
    public ResDes() 
    { } 
} 

Resdesitem class:

[DataContract()] 
public class ResDesItem 
{ 

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

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


    [XmlElement("Country")] 
    public EtResultDetAdritemCountry EtResultDetAdritemCountry { get; set; } 

    // CONSTRUCTOR 
    public ResDesItem() 
    { } 
} 
+0

你嘗試用'[Serializable]'屬性標記ResDesItem類嗎? – jglouie

+0

嗨,我目前正在爲手機平臺開發,所以我使用它的等價的[DataContract()],但它仍然是空的 – Bohrend

+0

「ResDesItem」類在哪裏?你可以粘貼這個類嗎? – jglouie

回答

1

* 注意:不要忘記在每個上添加[DataMember]屬性或類的成員*

如果你想與DataContract辦法做到這一點,以下列方式使用它:

[DataContract] 
[XmlRoot("item")] 
[XmlType] 
public class ResDesItem 
{ 
    [XmlElement("PoBox")] 
    [DataMember] 
    public string PoBox { get; set; } 
    [XmlElement("City1")] 
    [DataMember] 
    public string City1 { get; set; } 
    [XmlElement("Country")] 
    [DataMember] 
    public string Country { get; set; } 
} 

[DataContract] 
[XmlRoot("ResDes")] 
[XmlType] 
public class ResDes 
{ 
    [XmlElement("item")] 
    [DataMember] 
    public List<ResDesItem> ResDesItem { get; set; } 
} 

其餘是相同的分組答案我。

+0

爲什麼你回答兩次? –

+0

如果有人想使用[DataContract]做序列化,第二個答案將起作用,如果有人想用[Serializable]答案,第1個答案就可以工作。所以,我已經爲它添加了單獨的答案。 –

+0

@JohnSaunders,我需要刪除任何答案嗎? –

1

您需要創建兩個類爲:

[Serializable] 
[XmlRoot("ResDes")] 
[XmlType] 
public class ResDes 
{ 
    [XmlElement("item")] 
    public List<ResDesItem> ResDesItem { get; set; } 
} 

[Serializable] 
[XmlRoot("item")] 
[XmlType] 
public class ResDesItem 
{ 
    [XmlElement("PoBox")] 
    public string PoBox { get; set; } 
    [XmlElement("City1")] 
    public string City1 { get; set; } 
    [XmlElement("Country")] 
    public string Country { get; set; } 
} 

然後使用下面的代碼來反序列化,如:

 XmlSerializer xmlReq = new XmlSerializer(typeof(ResDes)); 
     string xml = @"<ResDes> <item><PoBox/><City1>South Korea</City1><Country>SK</Country> </item></ResDes>"; 

     Stream stream = new MemoryStream(Encoding.Unicode.GetBytes(xml)); 
     var resposnseXml = (ResDes)xmlReq.Deserialize(stream); 
+0

嗨Mahesh,我沒有嘗試上面的代碼,但是,而不是使用Serializable屬性我不得不使用DataContract,因爲它只能在Windows Phone中使用,但仍然不起作用 – Bohrend