看起来 SQL Server 在解析 XML 时删除了 \r
字符。因此,当我的存储过程接收到 xml 中的值以进行保存时,所有换行符都表示为 \n
而不是 \r\n.
有什么方法可以强制 SQL Server 不删除 \r
字符?在下面的示例中,Node1
值不包含 \r
符号。
DECLARE @hDoc int
DECLARE @Xml nvarchar(MAX)
SET @Xml = N'<Root><Node1><![CDATA[' + nchar(13) + nchar(10) + N'Some ' + nchar(13) + nchar(10) + N' Value]]></Node1></Root>'
EXEC sp_xml_preparedocument @hDoc OUTPUT, @Xml
SELECT
Node1
,convert(varbinary(max),Node1) -- Contains 0A00 in the start instead of 0D0A,
,charindex(nchar(13),Node1)
FROM
OPENXML(@hDoc, N'/Root', 2) WITH (Node1 NVARCHAR(MAX))
EXEC sp_xml_removedocument @hDoc
输出:
@PJB 建议使用XQuery nodes反而。但这没有帮助。我尝试在下面运行查询并得到相同的结果。
DECLARE @xml xml
SET @xml = convert(xml, N'<Root><Node1><![CDATA[' + nchar(13) + nchar(10) + N'Some ' + nchar(13) + nchar(10) + N' Value]]></Node1></Root>')
declare @Node1 nvarchar(30)
select @Node1 = node.value('.', 'nvarchar(30)')
from @xml.nodes('/Root/Node1') as doc(node)
SELECT
@Node1
,convert(varbinary(max),@Node1) -- Contains 0A00 in the start instead of 0D0A,
,charindex(nchar(13),@Node1)
最佳答案
Carriage return symbol is removed from XML
根据 End-of-Line Handling 上的 XML 规范,这是正确的行为.
the XML processor MUST behave as if it normalized all line breaks in external parsed entities (including the document entity) on input, before parsing, by translating both the two-character sequence #xD #xA and any #xD that is not followed by #xA to a single #xA character.
您可以尝试使用 replace返回回车。
select @Node1 = replace(node.value('.', 'nvarchar(30)'), nchar(10), nchar(13)+nchar(10))
from @xml.nodes('/Root/Node1') as doc(node)
关于sql - 使用 OPENXML 从 XML 中删除回车符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8281560/