需要XML DataContractDeserialization HELP

时间:2011-12-29 21:39:00

标签: c# xml serialization collections datacontractserializer

我有以下XML:

<?xml version="1.0" ?>
<Responses>
    <ResponseList>
      <Response type="XXX">
        <Foo>YYYY</Foo>
        <Bar>ZZZZ</Bar>
      </Response>
    </ResponseList>
</Responses>

我的类应该是什么样子,以便我可以将字符串反序列化为对象(我正在使用DataContractSerializer)

[DataContract(Namespace = "")]
[Serializable]
public class Responses : DataContainer
{
    [DataMember]
    public ResponseCollection ResponseList { get; set; }
}

[Serializable]
public class Response : DataContainer 
{
    [DataMember]
    public string Foo { get; set; }
    [DataMember]
    public string Bar { get; set; }
}

[Serializable]
public class ResponseCollection : List<Response>
{
}

[编辑] 我实际上能够使用DataContractSerializer ....我的目标是利用DataContractSerializer将XML字符串(响应)反序列化为对象,并且我为这两个属性获取NULL(foo&amp; bar)

[Serializable]
[DataContract(Namespace = "")]
public class Responses : DataContainer
{
    [DataMember(Name = "ResponseList")]
    public Response[] Response { get; set; }
}

[Serializable]
[DataContract(Namespace = "")]
public class Response : DataContainer
{
    [DataMember(Order = 0)]
    public string Foo { get; set; }
    [DataMember(Order = 1)]
    public string Bar { get; set; }
}

1 个答案:

答案 0 :(得分:2)

(这个答案在编辑之前提出了澄清需要DataContractSerializer的信息)

如果我正确理解了这个例子,那么如下所示。注意:其他属性没有坏处,但是XmlSerializer没有使用它 - 我只显示了XmlSerializer使用的那些。

[XmlRoot("Responses")]
public class TxTNotifyResponse : DataContainer
{
    [XmlArray("ResponseList")]
    [XmlArrayItem("Response")]
    public MsgResponseCollection MsgResponseList { get; set; }
}

public class MsgResponse : DataContainer 
{
    [XmlElement("Foo")]
    public string Status { get; set; }
    [XmlElement("Bar")]
    public string MessageId { get; set; }
}

public class MsgResponseCollection : List<MsgResponse>
{
}

如果这不起作用(我还没有测试过),请尝试使用单独的DTO模型。最简单的方法是将数据放在XML filE(例如,your.xml)中,并使用(在命令提示符下):

xsd.exe your.xml
xsd.exe your.xsd /classes

将编写your.cs