// 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.Collections.Generic; using System.IO; using System.Xml; 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); } private class MyXmlTextWriter : XmlTextWriter { private Dictionary repl; public MyXmlTextWriter(StreamWriter sw, Dictionary repl) : base(sw) { base.Formatting = Formatting.Indented; this.repl = repl; } public override void WriteStartElement(string prefix, string localName, string ns) { if(repl.ContainsKey(localName)) { base.WriteStartElement(prefix, repl[localName], ns); } else { base.WriteStartElement(prefix, localName, ns); } } } private class MyXmlTextReader : XmlTextReader { private Dictionary repl; public MyXmlTextReader(StreamReader sr, Dictionary repl) : base(sr) { this.repl = repl; } public override string LocalName { get { if(repl.ContainsKey(base.LocalName)) { return repl[base.LocalName]; } else { return base.LocalName; } } } } public static void Modifying() { Dictionary wrepl = new Dictionary(); wrepl.Add("Wrapper", "SomeWrapper"); wrepl.Add("Book", "GoodBook"); Dictionary rrepl = new Dictionary(); rrepl.Add("SomeWrapper", "Wrapper"); rrepl.Add("GoodBook", "Book"); 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(XmlWriter xw = new MyXmlTextWriter(new StreamWriter(@"C:\work\wrapper2.xml"), wrepl)) { xmlser.Serialize(xw, w); } Wrapper w2; using(XmlReader xr = new MyXmlTextReader(new StreamReader(@"C:\work\wrapper2.xml"), rrepl)) { w2 = (Wrapper)xmlser.Deserialize(xr); } Console.WriteLine(w2.Name + ": " + w2.Book.Title + "/" + w2.Book.Author); } public static void Main(string[] args) { Standard(); Modifying(); } } }