How to write a generic method to convert List<T> to xml string
<p>i got a routine from a site <code>http://www.dotnetcurry.com/ShowArticle.aspx?ID=428</code></p>

<p>see their code</p>

<pre><code>class Program
    {
        static void Main(string[] args)
        {
            List&lt;Employee&gt; empList = new List&lt;Employee&gt;();
            empList.Add(new Employee() { ID = 1, FName = "John", LName = "Shields", DOB = DateTime.Parse("12/11/1971"), Sex = 'M' });
            empList.Add(new Employee() { ID = 2, FName = "Mary", LName = "Jacobs", DOB = DateTime.Parse("01/17/1961"), Sex = 'F' });
            empList.Add(new Employee() { ID = 3, FName = "Amber", LName = "Agar", DOB = DateTime.Parse("12/23/1971"), Sex = 'M' });
            empList.Add(new Employee() { ID = 4, FName = "Kathy", LName = "Berry", DOB = DateTime.Parse("11/15/1976"), Sex = 'F' });
            empList.Add(new Employee() { ID = 5, FName = "Lena", LName = "Bilton", DOB = DateTime.Parse("05/11/1978"), Sex = 'F' });
        }
    }

    class Employee
    {
        public int ID { get; set; }
        public string FName { get; set; }
       public string LName { get; set; }
        public DateTime DOB { get; set; }
        public char Sex { get; set; }
    }
</code></pre>

<p>if anyone see this area of code which is generating xml from list then must notice the code is not generic rather it depends on List.
i want a generic routine which can convert any list to xml. specially if i could do by extension method.</p>

<pre><code>try
{
    var xEle = new XElement("Employees",
                from emp in empList
                select new XElement("Employee",
                             new XAttribute("ID", emp.ID),
                               new XElement("FName", emp.FName),
                               new XElement("LName", emp.LName),
                               new XElement("DOB", emp.DOB),
                               new XElement("Sex", emp.Sex)
                           ));

    xEle.Save("D:\\employees.xml");
    Console.WriteLine("Converted to XML");
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}
Console.ReadLine();
</code></pre>

<p>looking for help. thanks</p>

<h2>Edit</h2>

<p>I just customize <code>ToXml()</code> a bit but why it is throwing error? any idea?</p>

<pre><code>public static class utility
{
    public static string ToXml&lt;T&gt;(this T obj, string strContainer = "")
    {
        XmlSerializer serialize = null;

        if (strContainer.Trim() == "")
            serializer = new XmlSerializer(typeof(T));
        else
            serializer = new XmlSerializer(typeof(T), new XmlRootAttribute(strContainer));

        using (StringWriter sw = new StringWriter())
        {
            serializer.Serialize(sw, obj);
            return sw.ToString();
        }
    }
}
</code></pre>