繁体   English   中英

集合类型的XML序列化

[英]XML Serialization for collection types

是否有人有支持对象集合(例如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);
        }
    }
}

DataContractSerializer似乎是迄今为止最好的对象序列化器。 http://msdn.microsoft.com/zh-cn/library/system.runtime.serialization.datacontractserializer.aspx

你应该有类似的方法

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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