ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ToXML

Serializes an object to XML

Source

public static class XMLSerializeExtension
{
    public static string ToXML<T>(this T o)
        where T : new()
    {
        string retVal;
        using (var ms = new MemoryStream()) {
            var xs = new XmlSerializer(typeof(T));
            xs.Serialize(ms, o);
            ms.Flush();
            ms.Position = 0;
            var sr = new StreamReader(ms);
            retVal = sr.ReadToEnd();
        }
        return retVal;
    }
}

Example

public class Foo
{
    public string bar { get; set; }
    public List<string> baz { get; set; }
}

internal class Program
{
    private static void Main(string[] args)
    {
        var f = new Foo
                    {
                        bar = "hi",
                        baz = new List<string> {"quick", "brown", "fox"}
                    };
        Console.WriteLine(f.ToXML());

        //Output:
        //<?xml version="1.0"?>
        //<Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        //  <bar>hi</bar>
        //  <baz>
        //	<string>quick</string>
        //	<string>brown</string>
        //	<string>fox</string>
        //  </baz>
        //</Foo>
    }
}

Author: Jason Marcell

Submitted on: 27 okt. 2009

Language: C#

Type: System.Object

Views: 9674