-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();
        }
    }
}

I have got a generic serializeobject method that I wrote a while back. May be it will help you too.

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;
    }
}

Note: You may need to alter it as per your needs.

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 に答える