将任何类型的列表序列化为XML?

时间:2013-05-27 13:52:02

标签: c# .net xml linq xml-serialization

我有4个实体类。 A,B,C,D.它有不同的属性,如ID,地址甚至复杂的类型。我想写一个常用的方法,我可以传递任何列表,它将转换为XML。让我们说

public string GetAnyListtoXML(Any type of list)
        {
            string myXML=string.Empty;

return myXML;
        }

1 个答案:

答案 0 :(得分:1)

此方法允许您序列化您想要的任何内容。 您的实体类应该具有无参数构造函数。

此链接可能有助于控制序列化:http://msdn.microsoft.com/en-us/library/2baksw0z%28v=vs.100%29.aspx

    public string ObjectToXml<T>(T obj)
    {
        var stream = new StringWriter();

        string xmlDoc = string.Empty;
        try
        {
            var xmlSerializer = new XmlSerializer(typeof (T));
            xmlSerializer.Serialize(stream, obj);
            xmlDoc = stream.GetStringBuilder().ToString();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Błąd pliku xml: " + ex);
        }
        finally
        {
            stream.Close();
        }
        return xmlDoc;
    }



    public static T XmlToObject<T>(string xmlDoc)
    {
        var stream = new MemoryStream();
        byte[] xmlObject = Encoding.Unicode.GetBytes(xmlDoc);

        stream.Write(xmlObject, 0, xmlObject.Length);
        stream.Position = 0;
        T message;

        var ss = new XmlSerializer(typeof (T));
        try
        {
            message = (T) ss.Deserialize(stream);
        }
        catch (Exception)
        {
            message = default(T);
        }
        finally
        {
            stream.Close();
        }
        return message;
    }

如果你想这个方法只采用列表,你可以使用它:

    public string ObjectToXml<T>(List<T> obj)
    {
        var stream = new StringWriter();

        string xmlDoc = string.Empty;
        try
        {
            var xmlSerializer = new XmlSerializer(typeof (List<T>));
            xmlSerializer.Serialize(stream, obj);
            xmlDoc = stream.GetStringBuilder().ToString();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Błąd pliku xml: " + ex);
        }
        finally
        {
            stream.Close();
        }
        return xmlDoc;
    }