简体   繁体   中英

Error while deserializing XML from SQL Server

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">
<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.

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.

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);
    }
}

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:

Using StringWriter for XML Serialization

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM