rune711
rune711

Reputation: 339

Serializing XML into object - "error in xml document (2,2)

Yes, I have read other threads on this subject but I am missing something:

I am trying to deserialize an XML document that, in part, contains logged SMS messages. The XML file takes the format of:

<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>

My code looks like:

[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>();

}

I am trying to serialize it like this:

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

I get the error: "There is an error in XML document (2,2)" The inner exception states,<reports xmlns=''> was not expected.

I am sure it has something to do with the serializer looking for the namespace of the root node? Is my syntax correct above with the [XmlArray("reports")] ? I feel like something is amiss because "reports" is the root node and it contains a list of "report" items, but the decoration for the root node isn't right? This is my first foray into this area. Any help is greatly appreciated.

Upvotes: 0

Views: 89

Answers (1)

L.B
L.B

Reputation: 116138

With a minimal change to your non-compilable code

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>();

}

Upvotes: 2

Related Questions