簡體   English   中英

序列化為xml

[英]serialise to xml

我有一個類,我需要將其序列化為XML,但是只有特定的屬性,即不是全部。 最好的方法是什么? 另一種方法是創建屬性及其值的字典,然后序列化該字典。

看看XmlAttributes.XmlIgnore屬性 您需要做的就是用[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;
}

上面的答案很好用。 但是我不喜歡將所有內容都序列化而沒有指定字段的想法。 實際上,只是一個不同偏好的情況,我喜歡控制事物的工作方式。

使用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,它在結構復雜或較大的情況下提供較小的文件大小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM