Normally I use SQL Server or Oracle for storage, so serializing to XML is a little new for me. I've had trouble locating answers that mirror what I'm doing enough for me to grasp what I've done wrong.
I have object MyObject
and it has multiple properties. it is serializable
. I need to store an IEnumerable<MyObject>
to an xml file. This file is overwritten by a new list when saving, and when read needs to read directly back to an IEnumerable<MyObject>
again.
I've managed to suppress the XML declaration and everything just fine on writes past the first, but I'm stuck on how to store this in a way I can read it back. Existing code (partially from searching around on here):
foreach (var i in items)
{
bool append = File.Exists(fileName);
using (var file = new StreamWriter(fileName,append))
{
///don't add XML declarative headers if the file already exists.
if (append == true)
{
///check to see if the
var emptyNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
var settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
using (var writer = XmlWriter.Create(file, settings))
{
xml.Serialize(writer, i, emptyNamespaces);
}
}
else
{
xml.Serialize(file, i);
//append = true;
}
}
}
Obviously, I'm looping through the list, with only the first item having the XML header information. The problem is, I get multiple root nodes this way. if I create a new root node manually, I can't seem to serialize back to MyObject
> because it doesn't match a property or class. What approach should I use to be able to serialize and deserialize this list of objects?