user181218
user181218

Reputation: 1685

Incorrect XML deserialization

I have the following class:

public class FtpDefinition
{
    public FtpDefinition()
    {
        Id = Guid.NewGuid();
        FtpServerAddress = string.Empty;
        FtpPortSpecified = false;
        FtpPort = "21";
    }

    [System.Xml.Serialization.XmlElement("Id")]
    public System.Guid Id { get; set; }

    [System.Xml.Serialization.XmlElement("FtpServerAddress")]
    public string FtpServerAddress { get; set; }

    [System.Xml.Serialization.XmlElement("FtpPortSpecified")]
    public bool FtpPortSpecified  { get; set; }

    [System.Xml.Serialization.XmlElement("FtpPort")]
    public string FtpPort { get; set; }
}

I have a method that gets the following XML string, and using the .net XML deserialization capability deserializes it into an object of type FtpDefinition.

<FTPDefinition>
  <Id>a0a940a7-6785-41be-ac3a-75ba5d4c13ee</Id>
  <FtpServerAddress>ftp.noname.com</FtpServerAddress>
  <FtpPortSpecified>false</FtpPortSpecified>
  <FtpPort>21</FtpPort>
</FTPDefinition>

The problem is, that although the Id and FtpServerAddress fields get populated properly, FtpPort gets populated with an empty string, and what's more weird is that FtpPortSpecified gets populated with the bool value TRUE instead of FALSE.

I replaced the automatic properties in the above code with actual return\... = value old style getter\setter, so that I can catch the setter getting hit. I was suspecting there's some user code setting the value, but this is not the case. In the call stack it clearly shows that the .net deserialization code is calling the setter with the value TRUE, but one can also see that the XML string provided as parameter to the deserializing method has the correct value (FALSE).

The deserialization code is simple:

XmlSerializer xs =  ...(objectType);

using (StringReader stringReader = new StringReader(xml))
{
    return xs.Deserialize(stringReader);
}

Please help me figure out what's going on.

Upvotes: 0

Views: 448

Answers (1)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

The Specified suffix has some special behavior in XML Serialization. Simply change FtpPortSpecified to something else.
http://msdn.microsoft.com/en-us/library/office/bb402199(v=exchg.140).aspx

Upvotes: 1

Related Questions