将XML序列化为对象 - " xml文档中的错误(2,2)

时间:2014-06-19 17:31:38

标签: c# xml wpf

是的,我已经阅读了有关此主题的其他主题,但我遗漏了一些内容:

我正在尝试反序列化一个XML文档,该文档部分包含已记录的SMS消息。 XML文件采用以下格式:

<reports>
  <report>
   <sms_messages>
     <sms_message>
     <number>4155554432</number>
     <text>Hi!  How are you?</text>
    </sms_message>
    <sms_message>
     <number>4320988876</number>
     <text>Hello!</text>
    </sms_message>
   </sms_messages>
  </report>
</reports>

我的代码如下:

[XmlType("sms_message")]
public class SMSMessage
{
   [XmlElement("number")]
   public string Number {get;set;}
   [XmlElement("text")]
   public string TheText {get;set;}
}


[XmlType("report")]
public class AReport
{
   [XmlArray("sms_messages")]
   public List<SMSMessage> SMSMessages = new List<SMSMessage>();
}

[XmlRoot(Namespace="www.mysite.com", ElementName="reports", DataType="string", IsNullable=true)]
public class AllReports
{
   [XmlArray("reports")]
   public List<AReport> AllReports = new List<AReport>();

}

我正在尝试将其序列化为:

XmlSerializer deserializer = new XmlSerializer(typeof(AllReports));
TextReader tr = new StreamReader(this.tbXMLPath.text);
List<AllReports> reports;
reports = (List<AllReports>)deserializer.Deserialize(tr);
tr.close();

我收到错误:&#34; XML文档(2,2)中出现错误&#34;内部异常状态为<reports xmlns=''> was not expected.

我确定它与查找根节点命名空间的序列化程序有关?上面的语法是否正确[XmlArray(&#34; reports&#34;)]?我觉得有些不对劲,因为&#34;报告&#34;是根节点,它包含一个&#34;报告&#34;的列表。项目,但根节点的装饰是不是正确?这是我第一次涉足这个领域。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

不可编辑的代码进行最小的更改

XmlSerializer deserializer = new XmlSerializer(typeof(AllReports));
TextReader tr = new StreamReader(filename);
AllReports reports = (AllReports)deserializer.Deserialize(tr);

[XmlType("sms_message")]
public class SMSMessage
{
    [XmlElement("number")]
    public string Number { get; set; }
    [XmlElement("text")]
    public string TheText { get; set; }
}


[XmlType("report")]
public class AReport
{
    [XmlArray("sms_messages")]
    public List<SMSMessage> SMSMessages = new List<SMSMessage>();
}

[XmlRoot("reports")]
public class AllReports
{
    [XmlElement("report")]
    public List<AReport> Reports = new List<AReport>();

}