簡體   English   中英

SQL 服務器在投射到 XML 時丟失回車

[英]SQL Server loses carriage return when casting to and then back from XML

如果我將包含完整換行符 (\r\n) 的nvarchar字符串轉換為 XML,那么在轉換回來時,我發現生成的字符串只包含 \n 而不是 \r\n。

是否有控制此行為的服務器或連接選項?

declare 
  @ln nvarchar(2) = char(13)+char(10)

declare 
  @str nvarchar(max) = '<x>qwe '+@ln+' asd</x>'
print @str
print charindex(@ln, @str) -- found
/*  output: 8 */

-- convert to xml
declare @xml xml = convert(xml, @str)
-- convert back to str
set @str = convert(nvarchar(max), @xml)

print @str
print charindex(@ln, @str) -- not found
/*  output: 0 */
print charindex(char(13), @str) -- not found
/*  output: 0 */
print charindex(char(10), @str) -- found
/*  output: 8 */

此行為是設計使然。

來自可擴展標記語言 (XML) 1.0(第五版), 2.11 行尾處理

XML 解析的實體通常存儲在計算機文件中,為了編輯方便,這些文件被組織成行。 這些行通常由字符 CARRIAGE RETURN (#xD) 和 LINE FEED (#xA) 的某種組合分隔。

為了簡化應用程序的任務,XML 處理器必須表現得好像它在解析之前通過翻譯雙字符序列 #xD #xA 和任何 # 來規范化輸入的外部解析實體(包括文檔實體)中的所有換行符。 xD 后面沒有跟#xA 到單個#xA 字符。

如果您想在文本中保留回車符,您通常需要將它們轉換為實體編碼,例如&#xd; &#13; .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM