Passing the root to the xsd.exe, successfully generates the Classes with the proper structure according to the XSD,
we can now assign values to the objects of those classes and populate them, the question is how can we serialise them to XML output keeping the original
Your question is unclear, but perhaps your problem is as follows:
List<object>of objects that you need to serialize to a single XML file.I.e. if you have two objects that would individually serialize as:
You would like to generate an XML file like the following:
If so, the easiest approach may be to serialize each object to some intermediate
XDocument, then combine them into the final XML document. The following extension methods do this:And then you would serialize your
List<object> objectsas follows:Notes:
As explained by Marc Gravell in his answer to Memory Leak using StreamReader and XmlSerializer, if you construct an
XmlSerializerwith any other constructor thannew XmlSerializer(Type)ornew XmlSerializer(Type, String), you must statically cache and reuse the serializer to prevent a severe memory leak. The above code does this via a static dictionary protected vialockstatements. (This should also substantially improve performance.)You may want to throw an exception if the serialized objects have different root element names and/or root element attributes. See the
TODOin the above code for the location to put the necessary checks.The extension method above throws an exception if the collection of objects is empty. You may want to modify that, e.g. by writing some default root element, or by deleting the incomplete empty file.
Since you are generating your list of objects from the rows of a
DataTable dataTable, you might check to see whether simply writing the DataTable directly usingDataTable.WriteXml(filename, XmlWriteMode.IgnoreSchema)meets your requirements.Demo fiddle here.