Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I think I'm missing something in my C# Serialization understanding.

I am serializing a C# class to XML to transfer across a web service. For simplicity's sake, I have a class with only three properties:
C#
public partial class MyInfo : SerializableObject
{
   private string ssnField;
   private string suffixField;
   private integer suffixIDField;

   public MyInfo()
   {
      this.ssnField = string.Empty;
      this.suffixField = string.Empty;
      this.suffixIDField = 0;
   }

   public string SSN
   {
      get { return this.ssnField; }
      set { this.ssnField = value; }
   }
	
   public string Suffix
   {
      get { return this.suffixField; }
      set { this.suffixField = value; }
   }
   
   public integer SuffixID
   {
      get { return this.suffixIDField; }
      set { this.suffixIDField = value; }
   }
}


And here's the gist of the serializer:
C#
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8) { Formatting = Formatting.Indented })
{
   xmlSerializer.Serialize(xmlTextWriter, this);						
   memoryStream = (MemoryStream)xmlTextWriter.BaseStream;				
   xmlText = new UTF8Encoding().GetString(memoryStream.ToArray());
   memoryStream.Dispose();
}


And here's my output: Neither SSN or Suffix get set beyond the string.empty call. SSN shows up in the XML, Suffix does not. Anyone know why?

XML
<SSN />
<SuffixID>0</SuffixID>


I'd prefer to not pass empty fields (like Suffix) but I'd settle to know why one appears, and one does not.

Thanks much.
Posted
Updated 12-Dec-12 4:25am
v2
Comments
Pablo Aliskevicius 12-Dec-12 10:40am    
What happens if your string variables have actual values?
dexterama 12-Dec-12 10:42am    
They appear as they should - one appears one does not, if they have no value.

1 solution

I found the answer! It was an missing descriptor:

[XmlElement(IsNullable = true)]
public string SSN
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900