This is about as close as you can get (the Estimate attribute is always on) without implementing IXmlSerializable:
[XmlRoot("Val")] public class DecimalField { [XmlText()] public decimal Value { get; set; } [XmlAttribute("Estimate")] public bool Estimate { get; set; } }
With IXmlSerializable, your class looks like this:
[XmlRoot("Val")] public class DecimalField : IXmlSerializable { public decimal Value { get; set; } public bool Estimate { get; set; } public void WriteXml(XmlWriter writer) { if (Estimate == true) { writer.WriteAttributeString("Estimate", Estimate.ToString()); } writer.WriteString(Value.ToString()); } public void ReadXml(XmlReader reader) { if (reader.MoveToAttribute("Estimate") && reader.ReadAttributeValue()) { Estimate = bool.Parse(reader.Value); } else { Estimate = false; } reader.MoveToElement(); Value = reader.ReadElementContentAsDecimal(); } public XmlSchema GetSchema() { return null; } }
You can test your class as follows:
XmlSerializer xs = new XmlSerializer(typeof(DecimalField)); string serializedXml = null; using (StringWriter sw = new StringWriter()) { DecimalField df = new DecimalField() { Value = 12.0M, Estimate = false }; xs.Serialize(sw, df); serializedXml = sw.ToString(); } Console.WriteLine(serializedXml); using (StringReader sr = new StringReader(serializedXml)) { DecimalField df = (DecimalField)xs.Deserialize(sr); Console.WriteLine(df.Estimate); Console.WriteLine(df.Value); }
source share