无法为xml添加新属性以进行序列化

时间:2014-07-10 04:57:43

标签: c# xml xml-serialization

我有一个用[Serializable]属性标记的现有类,并且有一些原始对象和用户定义对象作为被序列化到xml文件的属性。到目前为止,一切正常。这是我的类定义的样子

    [Serializable]
public class MyPlan
{
    [XmlElement]
    public string PlanFolder { get; set; }

    private string _name;
   [XmlElement]
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    private SystemText _SystemText;
    [XmlElement]
    public SystemText SystemText
    {
        get
        {
            if (ReferenceEquals(_SystemText, null))
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.CoordinateSystemTextRequired));
            return _SystemText;
        }
        set
        {
            if (ReferenceEquals(value, null))
                throw new ArgumentNullException("value");
            _SystemText = value;
        }
    }

    private ObservableCollection<PlanData> _planData;
    [XmlArrayItem("PlanData")]
    public ObservableCollection<WellPad> PlanData
    {
        get { return _planData ?? (_planData = new ObservableCollection<PlanData>()); }
    }

    internal void Write(string plnDirectory)
    {
        var planDirectory = Path.Combine(plnDirectory, Key);
        if (!Directory.Exists(planDirectory))
            Directory.CreateDirectory(planDirectory);

        ObjectSerializer.Write(Path.Combine(planDirectory, fileName), this);
    }

    internal static PlanData Read(string name, string projectDirectory, string SystemFolder)
    {
        var planDirectory = Path.Combine(projectDirectory, SystemFolder, name);
        var path = Path.Combine(planDirectory, FileName);
        return Read(path);
    }

    internal static Plan Read(string path)
    {
        if (!Directory.Exists(Path.GetDirectoryName(path))
            || !File.Exists(path))
            throw new FileNotFoundException();
        return ObjectSerializer.Read<Plan>(path);
    }

    private Defaults _planDefaults
    [XmlElement]
    public Defaults PlanDefaults
    {
        get { return _planDefaults ?? (_planDefaults = new Defaults()); }
        set { _planDefaults = value; }
    }

    public ObservableCollection<Plan> _previousPlans
    [XmlArrayItem("Plan")]
    public ObservableCollection<Plan> previousPlans
    {
        get { return _previousPlans ?? (_previousPlans = new ObservableCollection<Plan>()); }
    }
}

现在我正在尝试添加一个新的字符串属性,它只有一个getter / setter并且是公共的,并且它也有一个[xmlElement]属性。由于某种原因,此属性未被序列化为xml文件。如果我将属性的类型更改为Integer或Double,那么它会被序列化。这是什么问题?

1 个答案:

答案 0 :(得分:0)

我认为这是因为你的领域没有初始化。将您的媒体资源初始化为String.Empty并尝试。