Bohn
Bohn

Reputation: 26919

Error on deserializing a simple XML into a class object

My XML looks like this:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfAddressDetails xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <AddressDetails>
    <DbServerName>2k8</DbServerName>
  </AddressDetails>
  <AddressDetails>
    <DbServerName>2k8R2D3</DbServerName>
  </AddressDetails>
</ArrayOfAddressDetails>

And I created two classes for it as follows:

public class AddressDetails
{
    public string DbServerName { get; set; }
}

}

and another class to hold a list of those:

   public class AddressList
    {
        public List<AddressDetails> addressList= new List<AddressDetails>() ;
    }

And this is how I am deserializng it:

    XmlSerializer deSerializer = new XmlSerializer(typeof(AddressList));
    TextReader reader = new StreamReader(@"C:\TEMP\MyXML.xml");
    Object obj = deSerializer.Deserialize(reader);
    AddressList adrsList = (AddressList)obj;
    reader.Close();

But on Deserialize method I get this error:

enter image description here

Upvotes: 2

Views: 65

Answers (1)

CodeNotFound
CodeNotFound

Reputation: 23230

You have to decorate:

  • AddressList class with XmlRoot attribute like this [XmlRoot("ArrayOfAddressDetails")]
  • addressList field with XmlElement attribute like this [XmlElement("AddressDetails")]

You have this at the end:

[XmlRoot("ArrayOfAddressDetails")]
public class AddressList
{
    [XmlElement("AddressDetails")]
    public List<AddressDetails> addressList = new List<AddressDetails>();
}

Upvotes: 1

Related Questions