Whilest using XML serialisation to keep a set of Tasks in my Customer/Project Management App I came across a series of strange occurences which I tied down the the error: "There is an error in XML document."
Basically, the XML parser has come across a character that it doesn't expect to see given the specified encoding. In my case I was using UTF8 encoding.
Now I was puzzled that although I was using UTF8 encoding, the GBP sign (£) was causing the error. It turns out that I was encoding using UTF8 but the deserialisation was using "Default" encoding - OOPS.
Anyway, once I'd discovered that and changed so that UTF8 was the encoding for serialisation AND deserialisation we were good to go.
So if you get this error, check your encoding.
My serialisation code is:
public static bool SaveWorkToXML(TWork[] workArray, TTask thisTask)
{
string output = "";
try
{
XmlSerializer ser = new XmlSerializer(typeof(TWork[]));
Stream s = new MemoryStream();
XmlTextWriter xmlWriter = new XmlTextWriter(s, Encoding.UTF8);
ser.Serialize(xmlWriter, workArray);
TextReader rdr = new StreamReader(s);
s.Position = 0;
output = rdr.ReadToEnd().Replace("\"",'"'.ToString());
xmlWriter.Close();
s.Close();
return SaveWork(thisTask, output); // SaveWork supplies SqlParameters to a stored procedure and returns T/F if inserted/updated OK
}
catch { }
return false;
}
and the Deserialisation code:
public static TWork[] LoadWork(TTask thisTask)
{
TWork[] workArray = null;
try
{
string sql = "SELECT * FROM tblWork WHERE [work_guid] = '" +
thisTask.Task_GUID + "'";
DataTable dt = GetDataTable(sql);
string xmlText = "";
if (dt != null && dt.Rows != null)
{
foreach (DataRow dr in dt.Rows)
{
xmlText = dr["work_details"].ToString();
break;
}
}
dt.Dispose();
XmlSerializer ser = new XmlSerializer(typeof(TWork[]));
Stream s = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(xmlText));
workArray = (TWork[])ser.Deserialize(s);
}
catch
{ }
return workArray;
}