2

I created a custom type for EmailAdres and used this type in a class called User:

    public class User
{
public string UserId { get; set; }
public string UserName { get; set; }
public int CompanyId { get; set; }
public EmailAdres Email { get; set; }

}

[Serializable]
public class EmailAdres 
{
string _adres;

public EmailAdres()//needed for serialization
{

}
public EmailAdres(string s)
{
  _adres = s;
}

public static implicit operator EmailAdres(string s)
{
  return new EmailAdres(s);
}
public static implicit operator string(EmailAdres s)
{
  return s._adres;
}

}

The User object is returned by a webservice but unfortunately the Email element is rendered empty:

<User>
<UserId>887339</UserId>
<UserName>Behhh, Joyce</UserName>
<CompanyId>6401970</CompanyId>
<Email/>
</User>

I presumed the implicit cast would do the trick.

public static implicit operator string(EmailAdres s)
Robert Pouleijn
  • 399
  • 2
  • 15

2 Answers2

1

XML Serialization requires that a class must have a parameterless constructor.

In addition, any class members that are not public are not serialized. Methods are not serialized. And properties that do not have both a get and a set accessor are not serialized.

Serializing nested objects is not a problem. Everything in .Net is an object.

EDIT: chack this answer .NET XML serialization

Community
  • 1
  • 1
Udan
  • 5,429
  • 2
  • 28
  • 34
0

You could indeed make the _adres property public. If you don't want to do that you can implement the interface IXmlSerializable on your custom class:

public class EmailAdres: IXmlSerializable
{
   string _adres;

   // other implementation stuff removed

    public void ReadXml(System.Xml.XmlReader reader)
    {
        _adres =  reader.ReadElementContentAsString();
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        writer.WriteValue(_adres);
    }

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        throw new NotImplementedException();
    }

}

rene
  • 41,474
  • 78
  • 114
  • 152
  • Thanks Rene, if I make the _adres public will it still be possible (using attributes eg) to render it like a single element: adres@server.com – Robert Pouleijn Oct 17 '12 at 12:11
  • I don't think so. Feel free to ask a new question referencing this question and answer. – rene Oct 17 '12 at 12:20