// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Xml; using System.Xml.Serialization; using System.Xml.Schema; namespace E { public class PhoneBook1 { public string FirstName { get; set; } public string LastName { get; set; } public int Phone { get; set; } } public class PhoneBook2 { [XmlElement(IsNullable=true)] public string FirstName { get; set; } [XmlElement(IsNullable=true)] public string LastName { get; set; } public int? Phone { get; set; } } public class PhoneBook3 : IXmlSerializable { public string FirstName { get; set; } public string LastName { get; set; } public int Phone { get; set; } public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader rdr) { throw new NotImplementedException("Arne forgot to add deserialization!"); } public void WriteXml(XmlWriter wrt) { wrt.WriteStartElement("FirstName"); wrt.WriteString(FirstName != null ? FirstName : ""); wrt.WriteEndElement(); wrt.WriteStartElement("LastName"); wrt.WriteString(LastName != null ? LastName : ""); wrt.WriteEndElement(); wrt.WriteStartElement("Phone"); wrt.WriteString(Phone != 0 ? Phone.ToString() : ""); wrt.WriteEndElement(); } } public class Program { public static void Main(string[] args) { PhoneBook1 pb1 = new PhoneBook1(); XmlSerializer ser1 = new XmlSerializer(typeof(PhoneBook1)); ser1.Serialize(Console.Out, pb1); PhoneBook2 pb2 = new PhoneBook2(); XmlSerializer ser2 = new XmlSerializer(typeof(PhoneBook2)); ser2.Serialize(Console.Out, pb2); PhoneBook3 pb3 = new PhoneBook3(); XmlSerializer ser3 = new XmlSerializer(typeof(PhoneBook3)); ser3.Serialize(Console.Out, pb3); } } }