Serialization works due to the idea that only data is serialized, not objects. So at deserialization time, the objects to deserialize are instantiated first, and then the data is deserialized.
So if you have an auditor, and you want to serialize the auditor's contents, you've to serialize all the data in the auditor in such a way that you can deserialize it back into objects.
If your auditor only contains entity objects, you can serialize them one by one. However, you've to know up front when to stop.
so it's ok to serialize the data as:
<entities>
<entity...
<entity...
</entities>
this gives you the ability to stop reading data.
So do:
writer.WriteStartElement("Entities"); // <Entities>
foreach (AuditInfoEntity auditInfoEntity in _auditInfoEntities)
{
auditInfoEntity.WriteXml(writer);
}
writer.WriteEndElement(); // </Entities>
for deserialization, you've to read till /Entities is seen. When you get the call to ReadXml, the reader is located at <Entities>. So do:
string startElementName = reader.LocalName;
while(reader.Read() && !((reader.LocalName == startElementName) && (reader.NodeType == XmlNodeType.EndElement)))
{
AuditInfoEntity toDeserialize = new AuditInfoEntity();
toDeserialize.ReadXml(Reader);
collection.Add(toDeserialize);
}
If you run into issues, don't worry nor panic. Hassling with XmlReaders/writers is a bit of a struggle at first. To check whether the xml looks ok, save the xml to a file so you can examine it (e.g in a webbrowser).
WHen deserializing and things go wrong, for example you miss an endelement or scan over it so everythign following it goes wrong), place a breakpoint in the auditor's ReadXml(reader) routine above and check at the end start of the while loop if the reader is indeed located at the start of an entity