0

When I run the xmlserializer on my class, it does not output the property I have specified for my nested observable collection. I have made sure it is public and have ensured it has a setter but it just isn't getting serialised.

Running the xmlserializer produces this:

<ArrayOfArrayOfNote>
  <ArrayOfNote>
    <Note>
     (Many Properties of Note)
    </Note>
    <Note>
     (Many Properties of Note)
    </Note>
  <ArrayOfNote>
  <ArrayOfNote>
    <Note>
     (Many Properties of Note)
    </Note>
    <Note>
     (Many Properties of Note)
    </Note>
  <ArrayOfNote>
</ArrayOfArrayOfNote>

When I am expecting it to produce something like this:

<ArrayOfArrayOfNote>
  <ArrayOfNote>
    <Title>SomeTitle</Title>
    <Note>
     (Many Properties of Note)
    </Note>
    <Note>
     (Many Properties of Note)
    </Note>
  <ArrayOfNote>
  <ArrayOfNote>
    <Title>SomeTitle</Title>
    <Note>
     (Many Properties of Note)
    </Note>
    <Note>
     (Many Properties of Note)
    </Note>
  <ArrayOfNote>
</ArrayOfArrayOfNote>

This is the code I am using for the xmlserializer (which I believe isn't the problem)

XmlSerializer serialiser = new XmlSerializer(typeof(NoteBookList));
TextWriter writer = new StreamWriter(@"Notes.xml");
serialiser.Serialize(writer, modules);
writer.Close();

This is the class that is not serialized as I am expecting


[Serializable]
public class NoteBook : ObservableCollection<Note>
{
    public NoteBook()
    {

    }
    public NoteBook(string title)
    {
        Title = title;
    }
    public string Title { get; set; }
}

Thanks!

Sam
  • 75
  • 3
  • 1
    No, there is no way to get both the properties and the contents for any .Net XML serializer only via attributes. You will need to replace the collection with a surrogate. See: [XmlSerialize a custom collection with an Attribute](https://stackoverflow.com/q/377486). Theoretically you could implement `IXmlSerializable` but I don't recommend it; see e,g, [How to serialize an `ICollection` that also has read/write properties to XML](https://stackoverflow.com/a/34247035). – dbc Sep 29 '19 at 23:19

1 Answers1

0

You class Notes needs to look like this :

    public class Notes
    {
        [XmlArray("ArrayOfArrayOfNote")]
        [XmlArrayItem("ArrayOfNote")]
        public NoteBook[] noteBook { get; set; } 

        public string Title { get; set; }
    }
jdweng
  • 33,250
  • 2
  • 15
  • 20