简体   繁体   中英

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.List 1[PC]' to type 'System.Collections.Generic.List 1[System.Collections.Generic.List`1[PC]]'.

Please Help

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.

It should be

typeof(T) 

instead of

List<T> 

XmlSerializer ser = new XmlSerializer(typeof(T), new XmlRootAttribute("TheRootElementName"));

this line in your code causing problem

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

its creating list of list than is not needed

XmlSerializer ser = new XmlSerializer(typeof(T), 

either you do above change or do below changes

There is problem with you method you need to change signature to

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

and call method as below

WriteXML<PC>(_PCList, "ss.xml"); 

By doing above change might resolve your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM