Monday, August 5, 2013

.NET: Deserialize error while parsing the XML

I was running some Serialize and Deserialize code  online, on hackerrank , I was getting several XML parsing when calling Deserialize
The code I was using
string fileName = "file.txt";
System.Xml.Serialization.XmlSerializer s =
    new System.Xml.Serialization.XmlSerializer(typeof(myObject));

System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName, true);
s.Serialize(sw, myObject);
sw.Close();
I was getting the below error

Unhandled Exception: System.Xml.XmlException: XML declaration cannot appear in this state

I did some search and found people talking about encoding problems, and I found some articles guiding to change the encoding, using XmlWriter instead of StreamWriter, I changed my code to below to see if this will impact my error.

System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
settings.Encoding = new System.Text.UnicodeEncoding(false, false);
settings.Indent = true;

string fileName = "file.txt";
System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(typeof(myObject));
System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(fileName, settings);
s.Serialize(xw, myObject);
xw.Close();
Error then changed, this gave me the below error

Unhandled Exception: System.Xml.XmlException: a name did not start with a legal character

Which means that the name was invalid, so I changed the encoding to be Ascii,  ASCIIEncoding

System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
settings.Encoding = new System.Text.ASCIIEncoding();
settings.Indent = true;
System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(typeof(mybject));
System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create("filename", settings);
s.Serialize(xw, myObject);
file.Close();
The last code run successfully, and I was able to write and read the file