考虑以下代码:
[Test]
public void StackOverflowQuestionTest()
{
const string connectionString = "enter your connection string if you wanna test this code";
byte[] result = null;
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var sqlCommand = new SqlCommand("declare @xml as xml = '<xml/>' SELECT convert(varbinary(max), @xml) as value"))
//using (var sqlCommand = new SqlCommand("SELECT convert(varbinary(max), N'<xml/>') as value"))
{
sqlCommand.Connection = connection;
using (SqlDataReader reader = sqlCommand.ExecuteReader())
{
while (reader.Read())
{
result = (byte[])reader["value"];
}
reader.Close();
}
}
}
string decodedString = new UnicodeEncoding(false, true).GetString(result);
var document = XElement.Parse(decodedString);
}
如果我运行此测试,我会收到一条带有消息的 XmlException:“根级别的数据无效。第 1 行,位置 1。” 事实证明,问题是被视为无效字符的“0xFFFE”前导码。请注意,如果我改用注释字符串,一切正常,这对我来说很奇怪。看起来 SqlServer 在 UCS-2 中使用 BOM 存储 XML 字符串,同时它在没有它的情况下存储 nvarchar 值。主要问题是:如何将此字节数组解码为不包含此前导码(BOM)的字符串?