1
[Serializable]
public class ProfilesCollection : ObservableCollection<Profile>
{  
    public ProfilesCollection()
    {            
    }
}

[Serializable]
public class Profile : ObservableCollection<SomeData>
{
    private string _name;        
    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Name"));
        }
    }

    public Profile()
    {
    }
}

[Serializable]
public class SomeData : INotifyPropertyChanged
{
    // some properties

    public SomeData()
    { ... }

    [field: NonSerialized]
    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged(string property)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(property));
    }
}

I am trying to serialize ProfilesCollection (or Profile) object using XmlSerializer:

using (var writer = new StreamWriter("1.xml"))
{
    var xs = new XmlSerializer(typeof(ProfilesCollection));
    xs.Serialize(writer, _profiles);
}

but .xml doesn't contain Name property which is in Profile class. Everything except that is ok. What should I do to fix that?

Alex P.
  • 3,697
  • 9
  • 45
  • 110
  • 1
    Possible duplicate of http://stackoverflow.com/questions/8633398/xmlserialize-an-observablecollection – Matthew Strawbridge Sep 30 '12 at 11:33
  • @MatthewStrawbridge I've tried to add [XmlInclude(typeof(Profile))] [XmlInclude(typeof(ProfilesCollection))] before SomeData class, but the same result. – Alex P. Sep 30 '12 at 11:56

2 Answers2

2

When XmlSerializer serializes a collection, it only looks at the items in the collection, not the other properties of the collection class. If you need to serialize the name, you need to do something like this:

public class Profile
{
    private string _name;        
    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Name"));
        }
    }


    private readonly ObservableCollection<SomeData> _data = new ObservableCollection<SomeData>();
    public ObservableCollection<SomeData> Data
    {
        get { return _data; }
    }

    public Profile()
    {
    }
}

BTW, the Serializable and NonSerialized attributes are not used by XmlSerializer, so you don't need them (and events are not serialized by XmlSerializer anyway)

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
0

I think your 1.xml file should have the same structure to the Profile class. (It should have a Name node?)

King King
  • 61,710
  • 16
  • 105
  • 130