序列化为xml

时间:2012-10-16 07:58:06

标签: c# .net xml serialization

我有一个类,我需要将它序列化为XML,但只有特定属性,即不是全部。最好的方法是什么?另一种方法是创建属性及其值的字典,然后序列化字典。

2 个答案:

答案 0 :(得分:3)

看看XmlAttributes.XmlIgnore Property。您需要做的就是使用[XmlIgnoreAttribute()]

装饰您不想序列化的字段

示例类:

// This is the class that will be serialized.  
public class Group
{
   // The GroupName value will be serialized--unless it's overridden. 
   public string GroupName;

   /* This field will be ignored when serialized--unless it's overridden. */
   [XmlIgnoreAttribute]
   public string Comment;
}

答案 1 :(得分:0)

上述答案效果很好。但我不喜欢所有序列化的想法,只有指定的字段不存在。只是一个不同偏好的情况,真的,我喜欢控制事情的运作方式。

使用ISerializable,它来自MS:“允许对象控制自己的序列化和反序列化。”和一些反思:

    // Required by ISerializable
    public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        FieldInfo[] fields = this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

        foreach (FieldInfo field in fields)
        {
            if (!IsSerializable(field))
                continue;

            info.AddValue(field.Name, field.GetValue(this));
        }
    }

    protected bool IsSerializable(FieldInfo info)
    {
        object[] attributes = info.GetCustomAttributes(typeof(SerializableProperty), false);

        if (attributes.Length == 0)
            return false;

        return true;
    }

“SerializableProperty”是我想要序列化的字段的空属性。

至于哪个序列化程序,完全取决于你。 XML非常好,因为您可以在以后阅读和编辑它。但是,我选择了BinaryFormatter,它可以在复杂或大型结构的情况下提供更小的文件大小。