使用 BCP 创建 XML 文件生成的文件对非 ASCII 字符的编码无效
Using BCP to create XML files produces files with invalid encoding for non-ASCII characters
重现问题,SQL代码:
CREATE TABLE dbo.FooTable(SomeString NVARCHAR(100));
INSERT INTO dbo.FooTable(SomeString)
VALUES('Degree symbol is °');
DECLARE @Code NVARCHAR(4000) = N'BCP "SELECT (SELECT SomeString FROM dbo.FooTable FOR XML PATH(''Foo''), ROOT(''BAR''), TYPE )" QUERYOUT "F:\Output\File.XML" -c -C RAW -T ';
EXEC xp_cmdshell @Code;
DROP TABLE dbo.FooTable;
它创建包含以下内容的文件:
<BAR><Foo><SomeString>Degree symbol is °</SomeString></Foo></BAR>
此类文件无法被 Internet Explorer 和 Firefox 识别为有效的 XML 文件(Chrome 产生错误 error on line 1 at column 23: Encoding error
)。如果我用记事本打开它们并另存为 Unicode(小端)- 它会打开并验证。
更新:
changing bcp
options to -T -w -r -t
seems to make XML valid for most XML consumers, but not Internet Explorer.
试试这个 -
IF OBJECT_ID('tempdb.dbo.##t') IS NOT NULL
DROP TABLE ##t
SELECT x = (
SELECT x
FROM (
VALUES (N'Degree symbol is °')
) t(x)
FOR XML PATH('Foo'), ROOT('BAR'), TYPE
)
INTO ##t
DECLARE @sql NVARCHAR(4000) = 'bcp "SELECT * FROM ##t" queryout "D:\sample.xml" -S ' + @@servername + ' -T -w -r -t'
EXEC sys.xp_cmdshell @sql
有趣的是你的问题的根源...
重现问题,SQL代码:
CREATE TABLE dbo.FooTable(SomeString NVARCHAR(100));
INSERT INTO dbo.FooTable(SomeString)
VALUES('Degree symbol is °');
DECLARE @Code NVARCHAR(4000) = N'BCP "SELECT (SELECT SomeString FROM dbo.FooTable FOR XML PATH(''Foo''), ROOT(''BAR''), TYPE )" QUERYOUT "F:\Output\File.XML" -c -C RAW -T ';
EXEC xp_cmdshell @Code;
DROP TABLE dbo.FooTable;
它创建包含以下内容的文件:
<BAR><Foo><SomeString>Degree symbol is °</SomeString></Foo></BAR>
此类文件无法被 Internet Explorer 和 Firefox 识别为有效的 XML 文件(Chrome 产生错误 error on line 1 at column 23: Encoding error
)。如果我用记事本打开它们并另存为 Unicode(小端)- 它会打开并验证。
更新:
changing
bcp
options to-T -w -r -t
seems to make XML valid for most XML consumers, but not Internet Explorer.
试试这个 -
IF OBJECT_ID('tempdb.dbo.##t') IS NOT NULL
DROP TABLE ##t
SELECT x = (
SELECT x
FROM (
VALUES (N'Degree symbol is °')
) t(x)
FOR XML PATH('Foo'), ROOT('BAR'), TYPE
)
INTO ##t
DECLARE @sql NVARCHAR(4000) = 'bcp "SELECT * FROM ##t" queryout "D:\sample.xml" -S ' + @@servername + ' -T -w -r -t'
EXEC sys.xp_cmdshell @sql
有趣的是你的问题的根源...