[ACCEPTED]-XML Serialize boolean as 0 and 1-constraints

Accepted answer
Score: 55

You can also do this by using some XmlSerializer 5 attribute black magic:

[XmlIgnore]
public bool MyValue { get; set; }

/// <summary>Get a value purely for serialization purposes</summary>
[XmlElement("MyValue")]
public string MyValueSerialize
{
    get { return this.MyValue ? "1" : "0"; }
    set { this.MyValue = XmlConvert.ToBoolean(value); }
}

You can also use other 4 attributes to hide this member from intellisense 3 if you're offended by it! It's not a perfect 2 solution, but it can be quicker than implementing 1 IXmlSerializable.

Score: 3

You can implement IXmlSerializable which 7 will allow you to alter the serialized output 6 of your class however you want. This will 5 entail creating the 3 methods GetSchema(), ReadXml(XmlReader 4 r) and WriteXml(XmlWriter r). When you implement 3 the interface, these methods are called 2 instead of .NET trying to serialize the 1 object itself.

Examples can be found at:

http://www.developerfusion.co.uk/show/4639/ and

http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx

Score: 1

No, not using the default System.Xml.XmlSerializer: you'd 8 need to change the data type to an int to 7 achieve that, or muck around with providing 6 your own serialization code (possible, but 5 not much fun).

However, you can simply post-process 4 the generated XML instead, of course, either 3 using XSLT, or simply using string substitution. A 2 bit of a hack, but pretty quick, both in 1 development time and run time...

More Related questions