2

I am trying to deserialize a Nullable<bool> from my XML file. My expectation was that a XMLAttribute which was not found in my XMLElement is null and if it's found it will be trueor false. Same for serialization. My variable will be written if it's not null.

Anyways, everytime I'm trying to deserialize my XML an InvalidOperationException will be thrown.

My class looks like this

[XMLArray("Users")]
public class User
{
    [XMLAttribute("copy")]
    public bool? copy;
}

Any ideas?

theknut
  • 2,533
  • 5
  • 26
  • 41
  • 1
    Have a look at this approach, the top answer to this: http://stackoverflow.com/questions/1295697/deserializing-empty-xml-attribute-value-into-nullable-int-property-using-xmlseri It basically wraps a property around the nullable bool and serialize/deserializes that one. Ignore the bool property from serialization. – lahsrah Jul 30 '12 at 07:15
  • 3
    You could use `public bool ShouldSerializecopy() {return copy.HasValue;}` as shown here : http://stackoverflow.com/questions/244953/serialize-a-nullable-int – Raphaël Althaus Jul 30 '12 at 07:16

1 Answers1

6
[XMLArray("Users")]
public class User
{
    [XmlIgnore]
    public bool? m_copy;

    [XmlAttribute("copy")]
    public string copy
    {
        get { return (m_copy.HasValue) ? m_copy.ToString() : null; }
        set { m_copy = !string.IsNullOrEmpty(value) ? bool.Parse(value) : default(bool?); }
    }
}

I got the solution from the answer to a post linked by sylon. Thanks alot!

Community
  • 1
  • 1
theknut
  • 2,533
  • 5
  • 26
  • 41