-1

I have a List<Object> which I am trying to serialize using the XmlSerializer and save to the disk but this piece of code generates an error while trying to serialize the file.

According to the thrown error message I get, I don't see anything wrong here and I think I need an extra pair of eyes on this.

Does anyone have a good idea as to why this keeps me awake all night? :/

I know the list contains the element so there is something going wrong with the types perhaps? Tried Type[] but it gives the same problem.

public static void createFileXml(String path)
{           
    //This creates an error while serializing
    XmlSerializer xmlser = new XmlSerializer(typeof(List<Object>));
    TextWriter txtwrt = new StreamWriter(path);
    try
    {
        xmlser.Serialize(txtwrt, lstCopy);
    }
    catch
    {
        throw;
    }
    finally
    {
        if (txtwrt != null)
        {
            txtwrt.Close();
        }
    }
}

In this case the array become associative. All PHP arrays are some sort of Associative arrays and are implemented as a hash table.

4

1 回答 1

1

我有一个通用的 serializeobject 方法,这是我不久前写的。也许它也会帮助你。

public static string SerializeObject<T>(T obj)
{
    try
    {
        string xmlString = null;
        using (MemoryStream memoryStream = new MemoryStream())
        {
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            UTF8Encoding enc = new UTF8Encoding();
            using (StreamWriter writer = new StreamWriter(memoryStream, enc))
            {
                XmlSerializer xs = new XmlSerializer(typeof(T));
                xs.Serialize(writer, obj, ns);
            }
            xmlString = enc.GetString(memoryStream.ToArray());
            return xmlString;
        }
    }
    catch
    {
        return string.Empty;
    }
}

注意:您可能需要根据需要对其进行更改。

于 2013-03-25T12:35:45.317 回答