Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# List<> to xml

Calling

List<PC> _PCList = new List<PC>();
...add Pc to PCList.. 
WriteXML<List<PC>>(_PCList, "ss.xml");

Function

public static void WriteXML<T>(T o, string filename)
{

    string filePath= Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Genweb2\\ADSnopper\\" + filename;

    XmlDocument xmlDoc = new XmlDocument();
    XPathNavigator nav = xmlDoc.CreateNavigator();
    using (XmlWriter writer = nav.AppendChild())
    {
        XmlSerializer ser = new XmlSerializer(typeof(List<T>), new XmlRootAttribute("TheRootElementName"));
        ser.Serialize(writer, o); // error
    }
    File.WriteAllText(filePath,xmlDoc.InnerXml);

}

inner exception

Unable to cast object of type 'System.Collections.Generic.List1[PC]' to type 'System.Collections.Generic.List1[System.Collections.Generic.List`1[PC]]'.

Please Help

like image 446
Taufiq Abdur Rahman Avatar asked Sep 26 '12 07:09

Taufiq Abdur Rahman


1 Answers

The problem is with the line

XmlSerializer ser = new XmlSerializer(typeof(List<T>), ...

Your T is already List<PC>, and you're trying to create typeof(List<T>), which will translate to typeof(List<List<PC>>). Simply make it typeof(T) instead.

like image 171
Igal Tabachnik Avatar answered Oct 08 '22 12:10

Igal Tabachnik