// 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.IO; using System.Xml.Serialization; namespace E { public class Book { public string Title { get; set; } public string Author { get; set; } } public class Wrapper { public string Name { get; set; } public Book Book { get; set; } } public class Program { public static void Standard() { Book o = new Book(); o.Title = "XML Serialization is fun"; o.Author = "Arne"; Wrapper w = new Wrapper(); w.Name = "Demo"; w.Book = o; XmlSerializer xmlser = new XmlSerializer(typeof(Wrapper)); using(StreamWriter sw = new StreamWriter(@"C:\work\wrapper.xml")) { xmlser.Serialize(sw, w); } Wrapper w2; using(StreamReader sr = new StreamReader(@"C:\work\wrapper.xml")) { w2 = (Wrapper)xmlser.Deserialize(sr); } Console.WriteLine(w2.Name + ": " + w2.Book.Title + "/" + w2.Book.Author); } public static void Modifying() { Book o = new Book(); o.Title = "XML Serialization is fun"; o.Author = "Arne"; Wrapper w = new Wrapper(); w.Name = "Demo"; w.Book = o; XmlAttributes attrs = new XmlAttributes(); attrs.XmlRoot = new XmlRootAttribute("SomeWrapper"); XmlAttributes attrs2 = new XmlAttributes(); attrs2.XmlElements.Add(new XmlElementAttribute("GoodBook")); XmlAttributeOverrides over = new XmlAttributeOverrides(); over.Add(typeof(Wrapper), attrs); over.Add(typeof(Wrapper), "Book", attrs2); XmlSerializer xmlser = new XmlSerializer(typeof(Wrapper), over); using(StreamWriter sw = new StreamWriter(@"C:\work\wrapper2.xml")) { xmlser.Serialize(sw, w); } Wrapper w2; using(StreamReader sr = new StreamReader(@"C:\work\wrapper2.xml")) { w2 = (Wrapper)xmlser.Deserialize(sr); } Console.WriteLine(w2.Name + ": " + w2.Book.Title + "/" + w2.Book.Author); } public static void Main(string[] args) { Standard(); Modifying(); } } }