无法切换编码

时间:2016-01-08 14:18:21

标签: c# sql-server xml

我正在从我的C#应用​​程序生成一个xml,然后我将其发送到SQL Server存储过程。当存储过程解析xml时,它会抛出错误

  

XML解析:第1行,第39个字符,无法切换编码

这是我生成XML的方式。该功能是一个扩展功能。

public static string ToXml<T>(this T obj, string rootName)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T), new XmlRootAttribute(rootName));

    var xmlNs = new XmlSerializerNamespaces();
    xmlNs.Add(string.Empty, string.Empty);

    using (StringWriter sw = new StringWriter())
    {
        serializer.Serialize(sw, obj, xmlNs);
        return sw.ToString();
    }
}

,存储过程如下所示:

/*
        SET @Data = '<?xml version="1.0" encoding="utf-16"?>
                    <Students>
                      <Student>
                        <ID>2</ID>
                        <FirstName>Soument</FirstName>
                        <LastName>Sen</LastName>
                        <IsActive>true</IsActive>
                        <StateID>2</StateID>
                        <StateName>Bihar</StateName>
                        <CityID>4</CityID>
                        <CityName>DharBganga</CityName>
                      </Student>
                    </Students>'  

*/
CREATE PROCEDURE [dbo].USP_SaveStudent
(
        @Data               xml,
        @PageNbr            INT = 1,
        @PageSize           INT = 10,
        @SortColumn         NVARCHAR(20) = 'ID',
        @SortOrder          NVARCHAR(4)= 'ASC'  
)
AS
BEGIN TRY
    MERGE INTO Student as Trg  
    USING (SELECT
               d.x.value('id[1]', 'varchar(MAX)') as ID,
               d.x.value('FirstName[1]', 'varchar(MAX)') as FirstName ,  
               d.x.value('LastName[1]', 'varchar(MAX)') as LastName,
               d.x.value('StateID[1]','int') as StateID,
               d.x.value('CityID[1]','int') as CityID,
               d.x.value('IsActive[1]','bit') as IsActive
           FROM
               @Data.nodes('/Students/Student') as  d(x)) AS Src ON Trg.ID = Src.ID  

    WHEN MATCHED THEN
        UPDATE 
            SET Trg.FirstName = Src.FirstName,  
                Trg.LastName = Src.LastName,
                Trg.StateID = Src.StateID,
                Trg.CityID = Src.CityID,
                Trg.IsActive = Src.IsActive

    WHEN NOT MATCHED BY TARGET THEN
        INSERT (FirstName, LastName, StateID, CityID, IsActive) 
        VALUES(Src.FirstName, Src.LastName, Src.StateID, Src.CityID, Src.IsActive);   
END TRY
BEGIN CATCH
    -- Insert Error into table
    --INSERT INTO #error_log(message)
    --VALUES (ERROR_MESSAGE());
END CATCH

EXEC USP_GetStudentData @PageNbr, @PageSize, @SortColumn, @SortOrder

寻找如何修复它的指导。感谢

1 个答案:

答案 0 :(得分:0)

XML标头中的encoding="utf-16"正在扼杀你。如果需要XML头,你可以摆脱编码吗?

来自MSDN的完整法律术语是here;关键是XML文档中的编码必须与包含XML文档的字符串的编码匹配。