简体   繁体   English

从SQL Server反序列化XML时出错

[英]Error while deserializing XML from SQL Server

I have an application which serializes and deserializes .NET objects to XML. 我有一个将.NET对象序列化和反序列化为XML的应用程序。 While deserializing I am getting the following error: 反序列化时,出现以下错误:

"There is an error in XML Document(1,2) Name cannot begin with the '.' “ XML文档(1,2)中存在错误,名称不能以'开头。 character, hexadecimal value 0x00. Line 1, position 2. " 字符,十六进制值0x00。第1行,位置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. LoanEntity是贷款表中的XML类型字段。

A snippet of the XML stored in the field: 存储在该字段中的XML的摘要:

<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. 我看到您已将字符串转换为UTF16字节数组。 Have you checked that is should not be UTF8 instead? 您是否检查过而不应该是UTF8? 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. 由于SQL Server XML字段期望值的Unicode类型编码,因此我尝试使用StringReader代替MemoryStream,到目前为止一切正常。 The following StackOverFlow post helped as well: 以下StackOverFlow帖子也有所帮助:

Using StringWriter for XML Serialization 使用StringWriter进行XML序列化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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