Serializing Objects to XML

On 2011/01/01, in Programming, by Greg Woods

Paste the following C# code directly in LINQPad, change language to ‘C# Program’ and run it.

void Main() {
    //create test object hierarchy with data
    var people = new List<Person>() {
        new Person() {
            Forename = "Greg",
            Surname = "Woods",
            Hobbies = new List<Hobby>() {
                new Hobby("Sailing"),
                new Hobby("Skiing")
            }
        },
        new Person() {
            Forename = "Alison",
            Surname = "Woods",
            Hobbies = new List<Hobby>() {
                new Hobby("Sleeping")
            }
        }        
    };    
    
    //do the serializing magic
    var x = new System.Xml.Serialization.XmlSerializer(people.GetType());
    var output = new StringBuilder();
    var xmlWriterSettings = new XmlWriterSettings() {
        Indent = true,
        IndentChars = ("\t"),
        CloseOutput = true
    };
    XmlWriter writer = XmlWriter.Create(output, xmlWriterSettings);
    x.Serialize(writer, people);
    writer.Close();
    
    //display the output in LINQPad
    output.ToString().Dump();
}

//Common classes used for the Serialize and Deserialize code examples
public class Person {
    public string Forename { get; set; }
    public string Surname { get; set; }
    public List<Hobby> Hobbies;
    
    public Person() {
        Hobbies = new List<Hobby>();
    }
}

public class Hobby {
    public string Name {get; set; }
    public Hobby()     {}        //required for serialisation to work, even though not used by my test code
    public Hobby(string name) {
        this.Name = name;    
    }    
}
Tagged with:  

2 Responses to Serializing Objects to XML

  1. Jayden says:

    Now I’m like, well duh! Truly thafnkul for your help.

  2. Yes, more white hat SEO please! And I think it’ll even exist in more than 5 years. There’s actually nothing wrong with SEO just as long as it isn’t black hat SEO.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>