Reputation:
Hard one to explain, can anybody spot what is wrong?
I am serialising a class to XML, but one of the properties (A public Class within the Class) is being given blank values in the XML.
I am creating my own Settings Class which i am serialising to XML and deserialising back into a class onload of the application.
I have put debug points into the Save method and the "ColourScheme" does have values but they are being blanked in the XML.
public class SettingsModel
{
// DECLARE: Settings File Location
private static string SettingsFilePath = String.Format(@"{0}\{1}\{2}", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Typhoeus BluePrint", "BluePrint_Settings.xml");
// DECLARE: Public Settings
public DateTime LastUpdated = System.DateTime.Now;
public string StylesheetName = "style.css";
public string WebPageName = "index.html";
public string ProjectDirectory = String.Format(@"{0}\{1}\{2}", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Typhoeus BluePrint", "Projects");
public ColourSchemeClass ColourScheme = new ColourSchemeClass();
public SettingsModel()
{
}
public void Save()
{
LastUpdated = System.DateTime.Now;
// DECLARE: File Stream Object
FileStream fs = new FileStream(SettingsFilePath, FileMode.OpenOrCreate);
// DECLARE: Serialisation Parameters
XmlSerializer ClassSerialiser = new XmlSerializer(typeof(SettingsModel));
// SERIALISE: This Class to XML
ClassSerialiser.Serialize(fs, this);
// CLOSE: File Stream
fs.Close();
}
}
Here is the ColourScheme Class
public class ColourSchemeClass
{
#region Objects
// DECLARE: Colour Scheme Properties
public Color BaseColour = ColorTranslator.FromHtml("#1E1E1E");
public Color HighlightColour = ColorTranslator.FromHtml("#414141");
public Color SelectedColour = Color.White;
#endregion
#region Constructors
public ColourSchemeClass()
{
}
public ColourSchemeClass (Color Base, Color Highlight, Color Selected)
{
BaseColour = Base;
HighlightColour = Highlight;
SelectedColour = Selected;
}
#endregion
}
Here is the XML after serialisation. (Extract because I can't seem to format it here) (Replaced Tag open and close with square brackets)
[ColourScheme]
[BaseColour/]
[HighlightColour/]
[SelectedColour/]
[/ColourScheme]
Upvotes: 1
Views: 41
Reputation: 116731
Color
is immutable (no setters) so it can't be usefully serialized by XmlSerializer
. You need to introduce a proxy property for each Color property, for instance:
[XmlIgnore]
public Color BaseColour { get; set; }
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[XmlElement("BaseColour")]
public string XmlBaseColour
{
get
{
return ColorTranslator.ToHtml(BaseColour);
}
set
{
BaseColour = ColorTranslator.FromHtml(value);
}
}
Upvotes: 0