使用格式未知的DataContractSerializer进行c#xml反序列化

时间:2016-04-27 12:16:22

标签: c# xml deserialization

我的XML包含统计数据,如下所示:

<?xml version="1.0"?>
-<response>
<responsecode>0</responsecode>
<count>2</count>
-<statistics>
<id>id</id>
<msisdn>somemsisdn</msisdn>
</statistics>
-<statistics>
<id>otherid</id>
<msisdn>othermsisdn</msisdn>
</statistics>
</response>

我尝试反序列化它,但是如果有两个以上的记录 - 将添加更多的元素,看起来它们不能在某种列表或数组中反序列化,即我不知道XML的确切格式。

这是我的代码:

 [DataContract(Name = "response", Namespace = "")]
    class XMLStat
    {
        [DataMember(Order = 0)]
        public int responsecode;
        [DataMember(Order = 1)]
        public int count;
        [DataMember(Order = 2)]
        public List<StatElement> statistics;
        //public XMLStat() { statistics = new List<StatElement>(); }
    }

    [CollectionDataContract(ItemName="statistics", Namespace="")]
    class StatElement
    {
        [DataMember(Order = 0)]
        public string id;
        [DataMember(Order = 1)]
        public string msisdn;
    }

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(someurl);
            string result = string.Empty;
            DataContractSerializer ser = new DataContractSerializer(typeof(XMLStat));
            XMLStat stat = new XMLStat();
            using (var s = req.GetResponse().GetResponseStream())
                stat = (XMLStat)ser.ReadObject(s);

它序列化响应码和计数,但列表为空。我是否正确地假设这不是一个列表(并且有任何解决方法),或者我做错了什么?

1 个答案:

答案 0 :(得分:0)

使用XmlSerializer,这将成功反序列化输入:

假设你有这个输入xml:

string xmlText = "<?xml version='1.0'?> " +
  "<response>" +
    "<responsecode>0</responsecode>" +
    "<count>2</count>" +
    "<statistics>" +
       "<id>id</id>" +
       "<msisdn>somemsisdn</msisdn>" +
    "</statistics>" +
    "<statistics>" +
       "<id>otherid</id>" +
       "<msisdn>othermsisdn</msisdn> " +
    "</statistics>" +
  "</response> ";

你的班级:

  [XmlRoot("response")]
  public class XMLStat
  {
    public int responsecode;
    public int count;
    [XmlElement("statistics")]
    public List<StatElement> statistics;
  }

  public class StatElement
  {
    public string id;
    public string msisdn;
  }

然后反序列化:

XMLStat obj = new XMLStat();
var ser = new XmlSerializer(typeof(XMLStat));
using (var strReader = new StringReader(xmlText))
using (var reader = XmlReader.Create(strReader))
{
     obj = (XMLStat)ser.Deserialize(reader);
}