2014-02-07 17 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