I’m having some issues using XmlSerializer and XmlTextReader in c# when saving DataTables which do not contain any data. Is this a known issue and is there a workaround? When an empty datatable is saved using XMLSerializer the following XML is generated:
<Values> <xs:schema id='NewDataSet' xmlns='' xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'> <xs:element name='NewDataSet' msdata:IsDataSet='true' msdata:MainDataTable='Values' msdata:UseCurrentLocale='true'> <xs:complexType> <xs:choice minOccurs='0' maxOccurs='unbounded'> <xs:element name='Values'> <xs:complexType> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> <diffgr:diffgram xmlns:msdata='urn:schemas-microsoft-com:xml-msdata' xmlns:diffgr='urn:schemas-microsoft-com:xml-diffgram-v1' /> </Values>
When the XML containing this is reloaded XMLTextReader fails silently and does not load content beyond the point at which the empty datatable is written to the XML. This issue appears to be caused by the lack of an xs:sequence / xs:element entry inside xs:complexType. Is this a bug and if so what is the workaround?
The following c# program demonstrates the issue. It will output dt3 is null due to the issue described above:
public class Data { private DataTable dt1; private DataTable dt2; private DataTable dt3; public DataTable Dt1 { get { return dt1; } set { dt1 = value; } } public DataTable Dt2 { get { return dt2; } set { dt2 = value; } } public DataTable Dt3 { get { return dt3; } set { dt3 = value; } } public void TestDataTables() { if(dt1 == null) Console.WriteLine('dt1 is null'); if (dt2 == null) Console.WriteLine('dt2 is null'); if (dt3 == null) Console.WriteLine('dt3 is null'); } } class Program { static void Main(string[] args) { // Create test object Data data = new Data(); data.Dt1 = new DataTable('Test1'); data.Dt1.Columns.Add('Foo'); data.Dt2 = new DataTable('Test2'); // Adding the following line make serialization work as expected //data.Dt2.Columns.Add('Foo'); data.Dt3 = new DataTable('Test3'); data.Dt3.Columns.Add('Foo'); data.TestDataTables(); // Save to XML TextWriter filewriter = new StreamWriter('foo.xml'); XmlTextWriter writer = new XmlTextWriter(filewriter); writer.Formatting = Formatting.Indented; XmlSerializer s1 = new XmlSerializer(typeof(Data)); s1.Serialize(writer, data); writer.Close(); filewriter.Close(); // Reload from XML TextReader filereader = new StreamReader('foo.xml'); XmlTextReader reader = new XmlTextReader(filereader); XmlSerializer s2 = new XmlSerializer(typeof(Data)); Data newData = s2.Deserialize(reader) as Data; newData.TestDataTables(); } }
(after the edit)
Thanks for the example code. Yes, I’d agree that this is a bug. For workarounds… well, you could add a column by default? To avoid the cross-contamination, you could use
ShouldSerialize*:At least then it is dt2 that gets omitted, instead of dt3.