Click here to Skip to main content
12,401,832 members (61,193 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C# XML serialization
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:
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:
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?

<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 12-Dec-12 4:17am
dexterama7.9K
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

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

I found the answer! It was an missing descriptor:

[XmlElement(IsNullable = true)]
public string SSN
  Permalink  

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


Advertise | Privacy | Mobile
Web02 | 2.8.160721.1 | Last Updated 12 Dec 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100