.Net Settings file, complex types and serialization
-
01-10-2019 - |
Question
I have the following types
[Serializable, XmlType(Namespace="http://mycompany/foo"]
public sealed class Limit
{
[XmlElement(ElementName="Value1")]
public double Value1 {get;set;}
[XmlElement(ElementName="ComplexValue1")]
public ComplexValue ComplexValue1 {get;set;}
}
[Serializable, XmlType(Namespace="http://mycompany/foo"]
public sealed class ComplexValue
{
[XmlElement(ElementName="Item1")]
public double Item1 {get;set;}
[XmlElement(ElementName="Item2")]
public double Item2 {get;set;}
}
which I want to serialize to a .settings file.
When I copy the blob below into the settings file, I lose the ComplexValue1 element somehow:
<?xml version="1.0" encoding="utf-16"?>
<Limit>
<Value1>20</Value1>
<ComplexValue1>
<Item1>2.0</Item1>
<Item2>5.0</Item2>
</ComplexValue1>
</Limit>
i.e. Visual Studio transforms it to:
<?xml version="1.0" encoding="utf-16"?>
<Limit>
<Value1>20</Value1>
</Limit>
with a bunch of namespaces that I think don't matter for the question...
What am I missing?
Solution
You don't need the
Serializable
attribute for XML serializationI guess you should remove the
XmlType
attribute to solve the issue.You specify a namespace but there are none in the XML file? This should fit too.
Use
XmlRoot
for the root node if you like
OTHER TIPS
Generating the code for the default value can be switched off on a per-setting base within the Setting designer. Just set GenerateDefaultValueInCode to false within the property window for those settings that don't need it.