I have two classes which need to be in same xml file. The way the classes are done mean I’m having to serialize separately. Which I have managed to do. The first I do using TextWriter.
TextWriter writer = new StreamWriter(filepath);
serializer.Serialize(writer, class, ns);
This works fine. Then I wanted to add another class to the file. So did same but added that I want to append not overwrite.
TextWriter writer = new StreamWriter(filepath, true);
This adds the new class to end but also adds another declaration so my XML file reads.
<?xml version="1.0" encoding"utf-8"?>
<dog>
...
</dog>
<?xml version="1.0" encoding"utf-8"?>
<cat>
...
</cat>
I’ve tried to use XmlWriter so I could use XmlWriterSettings then chose false for OmitXmlDeclaration but then it overrides the previous class I serialized.
Your XML needs a root element to be valid XML.
You could create a
List<Animal>and serialize it. But if you do not have the same superclass, you can try to create a class like this:in the
ReadXmlandWriteXmlyou could use the generic serializer to serialize those objects then use the XmlWriter to write a startElement. endElement and include the serialized animal.