C# 集合类型的XML序列化

C# 集合类型的XML序列化,c#,serialization,xml-serialization,C#,Serialization,Xml Serialization,是否有人有支持集合的对象序列化实现,如ICollection、IEnumerable、IList、IDictionary 下面是我的实现,它不是那么干净 [Serializable] public abstract class IXmlable { public virtual string ToXml() { Type type = GetType(); PropertyInfo[] properties = type.GetProperties

是否有人有支持集合的对象序列化实现,如ICollection、IEnumerable、IList、IDictionary

下面是我的实现,它不是那么干净

[Serializable]
public abstract class IXmlable
{
    public virtual string ToXml()
    {
        Type type = GetType();
        PropertyInfo[] properties = type.GetProperties();

        string ret = "<" + type.Name + ">";
        foreach (PropertyInfo item in properties)
        {
            object value = item.GetValue(this, null);
            if (value is IConvertible)
                ret += ("<" + item.Name + ">" + (value as IConvertible).ToString(CultureInfo.GetCultureInfo("en-US")) + "</" + item.Name + ">").Replace("&", "&amp;");
            else
                ret += ("<" + item.Name + ">" + (value != null ? value.ToString() : String.Empty) + "</" + item.Name + ">").Replace("&", "&amp;");
        }
        ret += "</" + type.Name + ">";
        return ret;
    }

/// <summary>
/// A class for serializing objects
/// </summary>
public static class Serializer
{
    public static string ToXML<T>(this List<T> parameter)
    {
        return SerializeObject(parameter);
    }

    /// <summary>
    /// This function serialize object.
    /// </summary>
    /// <param name="parameters">The object to be serialize</param>
    /// <returns>Returns the XML presentation of serialized object</returns>
    public static string SerializeObject(params object[] parameters)
    {
        var doc = new XDocument(new XElement("root"));
        string swString = string.Empty;
        foreach (var parameter in parameters)
        {
            var list = parameter as IEnumerable;
            IXmlable xmlable;
            if (list != null)
            {
                Type type = list.GetType().GetGenericArguments()[0];
                if (type.BaseType != null && type.BaseType.Name == "IXmlable")
                {
                    string typeName = type.Name;
                    swString = "<?xml version=\"1.0\"?><ArrayOf" + typeName + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">";
                    swString = list.Cast<IXmlable>().Aggregate(swString, (current, item) => current + item.ToXml());
                    swString += "</ArrayOf" + typeName + ">";
                }
            }
            else if ((xmlable = parameter as IXmlable) != null)
            {
                swString = xmlable.ToXml();
            }
            else
            {
                swString = Serialize(parameter);
            }

            doc.Root.Add(XDocument.Parse(swString).Root);
        }
        return doc.ToString();
    }

    /// <summary>
    /// Serializes the specified parameter.
    /// </summary>
    /// <param name="parameter">The parameter.</param>
    /// <returns></returns>
    private static string Serialize(object parameter)
    {
        using (var sw = new MemoryStream())
        {
            new XmlSerializer(parameter.GetType()).Serialize(sw, parameter);
            sw.Position = 0;
            var buffer = new byte[sw.Length];
            sw.Read(buffer, 0, (int)sw.Length);
            return Encoding.Default.GetString(buffer);
        }
    }
}
[可序列化]
公共抽象类IXmlable
{
公共虚拟字符串ToXml()
{
Type=GetType();
PropertyInfo[]properties=type.GetProperties();
字符串ret=“”;
foreach(属性中的PropertyInfo项)
{
对象值=item.GetValue(此值为空);
如果(值是可转换的)
ret++=(“”+(值作为IConvertible)。ToString(CultureInfo.GetCultureInfo(“en-US”)+“”)。替换(“&”,”、“&;”);
其他的
ret+=(“”+(value!=null?value.ToString():String.Empty)+“”。替换(“&”,“&;”);
}
ret+=”;
返回ret;
}
/// 
///用于序列化对象的类
/// 
公共静态类序列化程序
{
公共静态字符串ToXML(此列表参数)
{
返回序列化对象(参数);
}
/// 
///此函数用于序列化对象。
/// 
///要序列化的对象
///返回序列化对象的XML表示形式
公共静态字符串序列化对象(参数对象[]参数)
{
var doc=新的XDocument(新的XElement(“根”);
string swString=string.Empty;
foreach(参数中的var参数)
{
var list=参数为IEnumerable;
IXmlable XML;
如果(列表!=null)
{
类型Type=list.GetType().GetGenericArguments()[0];
if(type.BaseType!=null&&type.BaseType.Name==“IXmlable”)
{
字符串typeName=type.Name;
swString=“”;
swString=list.Cast().Aggregate(swString,(current,item)=>current+item.ToXml());
swString+=“”;
}
}
else if((xmlable=参数为IXmlable)!=null)
{
swString=xmlable.ToXml();
}
其他的
{
swString=序列化(参数);
}
doc.Root.Add(XDocument.Parse(swString.Root));
}
返回doc.ToString();
}
/// 
///序列化指定的参数。
/// 
///参数。
/// 
私有静态字符串序列化(对象参数)
{
使用(var sw=new MemoryStream())
{
新的XmlSerializer(parameter.GetType()).Serialize(sw,parameter);
开关位置=0;
var buffer=新字节[sw.Length];
软件读取(缓冲区,0,(整数)软件长度);
返回Encoding.Default.GetString(缓冲区);
}
}
}

您应该有如下方法

private static void Save(T yourobject, Type[] extraTypesInyourObject, string path)
{
    using (TextWriter textWriter = new TextWriter(path))
    {
        XmlSerializer xmlSerializer = CreateXmlSerializer(extraTypes);
        xmlSerializer.Serialize(textWriter, yourobject);
    }
}

    private static XmlSerializer CreateXmlSerializer(Type[] extraTypes)
    {
        Type ObjectType = typeof(T);
        XmlSerializer xmlSerializer = null;
        if (extraTypes!=null)
        {
            xmlSerializer = new XmlSerializer(ObjectType, extraTypes);
        }
        else
        {
            xmlSerializer = new XmlSerializer(ObjectType);
        }

        return xmlSerializer;
    }

DataContractSerializer似乎是目前最好的对象序列化程序。

ICollection、IEnumerable、IList、IDictionary不是“泛型”类型…?不,你说得对,它们是具有泛型类型的集合接口。类型System.collections.generic.Dictionary`2[[System.String,mscorlib,Version=4.0.0.0,Culture=neutral,PublicKeyToken=B77A561934E089],不支持[System.String,mscorlib,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089]],因为它实现了IDictionary。如果您的字典有自己的类对象,则应将其添加到extraTypes类型数组中…type[]extraTypes=new type[]{dictionary}然后创建xml序列化程序。假设您要序列化的对象是您自己对象类型的集合。创建一个具有Dictionary yourObjects属性的集合对象;我尝试使用.var d=new Dictionary{{one”,“apple”},{two”,“orange”};xml.SaveToDocumentFormat(d,new type[]{typeof(Dictionary)},@”C:\1.xml”);我得到了:类型System.Collections.Generic.Dictionary`2[[System.String,mscorlib,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089],[System.String,mscorlib,Version=4.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089],[System.String,mscorlib,Version=4.0.0,Culture=neutral,PublicKeyToken=B77A5C5。