SQL Server FOR XML Enclosing Element?

你离开我真会死。 提交于 2019-11-28 02:06:14

It is not possible to have the xml processing instruction in a xml datatype in sql server. See Limitations of the xml Data Type

This code

declare @XML xml =  
  '<?xml version="1.0"?>
   <root>Value</root>'

select @XML

Has the output

<root>Value</root>

You can build the xml as a string with the xml processing instruction in place.

declare @XML xml = '<root>Value</root>'
declare @XMLStr nvarchar(max) = '<?xml version="1.0"?>'

set @XMLStr = @XMLStr + cast(@XML as nvarchar(max))

select @XMLStr

Output

--------------------------------------------------------------------------
<?xml version="1.0"?><root>Value</root>

Add "WITH XMLNAMESPACES" to the beginning and a ROOT() to the FOR XML clause:

WITH XMLNAMESPACES ( DEFAULT 'http://namespace_uri_here' )
SELECT * 
FROM TABLE
FOR XML AUTO, ROOT('TopLevel')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!