I'm trying to deserialize an XML file with XmlSerializer. However i am getting this exception: There is an error in XML document (1, 41).InnerException Message "ReplicationStatus xmlns='DistributionServices' was not expected."
The XML file looks like this:
<?xml version="1.0" encoding="UTF-8" ?>
<ts:Status xmlns:ts="DistributionServices">
<Server>DUMMY</Server>
<Object>DUMMY</Object>
<Port>123</Port>
<Code>DUMMY</Code>
<Key>b0ed5e56</Key>
</ts:Status>
The code that I have used is as follows:
MessageData data = new MessageData();
XmlSerializer xmlSerializer = new XmlSerializer(data.GetType());
data = (MessageData)xmlSerializer.Deserialize(new StringReader(msgData));
Here, msgData is the string containing the xml shown above. MessageData class looks like this:
[Serializable,XmlType("Status")]
public class MessageData
{
[XmlElement("Server")]
public string Server { get; set; }
[XmlElement("Object")]
public string Object { get; set; }
[XmlElement("Port")]
public string Port { get; set; }
[XmlElement("Code")]
public string Code { get; set; }
[XmlElement("Key")]
public string Key { get; set; }
}
Please let me know what I am doing wrong.
You have to declare the namespace in your class and set it to empty on your properties. Change your class model to this and it should work fine.
[Serializable, XmlRoot("Status", Namespace = "DistributionServices")]
public class MessageData
{
[XmlElement(Namespace = "")]
public string Server { get; set; }
[XmlElement(Namespace = "")]
public string Object { get; set; }
[XmlElement(Namespace = "")]
public string Port { get; set; }
[XmlElement(Namespace = "")]
public string Code { get; set; }
[XmlElement(Namespace = "")]
public string Key { get; set; }
}
BTW: you don't have to name XmlElement
's explicit if they have the same name as the property.