views:

38

answers:

3

I have an application which serializes and deserializes .NET objects to XML. While deserializing I am getting the following error:

"There is an error in XML Document(1,2) Name cannot begin with the '.' character, hexadecimal value 0x00. Line 1, position 2. "

The code snippet that does the deserializing is:

string xmlEntity = _loanReader["LoanEntity"].ToString();
XmlSerializer xs2 = new XmlSerializer(typeof(Model.Loan));
MemoryStream memoryStream2 = new MemoryStream(StringFunction.StringToUTF16ByteArray(xmlEntity));
XmlTextWriter xmlTextWriter2 = new XmlTextWriter(memoryStream2, Encoding.Unicode);
_loan = (Model.Loan)xs2.Deserialize(memoryStream2);

I am using a datareader to get the resultset from the stored procedure. LoanEntity is an XML type field in the loan table.

A snippet of the XML stored in the field:

<Loan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
<GUID>d2cc9dc3-45b0-44bd-b9d2-6ef5e7ddb54c</GUID><LoanNumber>DEV999999</LoanNumber>
....

I have spent countless hours trying to figure out what the error means but to no avail. Any help will be appreciated.

A: 

This is usually an issue with encoding. I see you have the string bring converted to a UTF16 byte array. Have you checked that is should not be UTF8 instead? I would give that a go and see what comes of it. Basically the deserializer might be looking for a different encoding.

Tim C
Hi Tim, Initially I was using UTF-8 encoding by default but had to switch to Unicode/UTF-16 because I was getting the error:"XML parsing: line 1, character 38, unable to switch the encoding"Switching to Unicode allowed me to write the serialized objects to the SQL server database.
fjxx
A: 

You must be working from an old example, and a bad one. Try this:

string xmlEntity = _loanReader["LoanEntity"].ToString();
XmlSerializer xs2 = new XmlSerializer(typeof(Model.Loan));
using (MemoryStream memoryStream2 = new MemoryStream(StringFunction.StringToUTF16ByteArray(xmlEntity)))
{
    XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.Unicode};
    using (XmlWriter writer = XmlWriter.Create(memoryStream2, settings))
    {
        _loan = (Model.Loan)xs2.Deserialize(memoryStream2);
    }
}
John Saunders
Thanks John - I tried this and now I am getting the error:"There is an error in XML document (1, 1).""Data at the root level is invalid. Line 1, position 1."
fjxx
A: 

I believe I may have found a solution to this. Since SQL Server XML field expects Unicode type encoding of values, I tried using a StringReader instead of a MemoryStream and things work well so far. The following StackOverFlow post helped as well:

http://stackoverflow.com/questions/1564718/using-stringwriter-for-xml-serialization

fjxx