SQL Server FOR XML Enclosing Element?

后端 未结 2 1472
被撕碎了的回忆
被撕碎了的回忆 2020-12-07 03:58

Using SQL Server 2008, I have a query that emits a result set using FOR XML. Right now it is a non-compliant fragment.

How can I wrap my result XML in an enclosing e

相关标签:
2条回答
  • 2020-12-07 04:12

    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')
    
    0 讨论(0)
  • 2020-12-07 04:18

    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>
    
    0 讨论(0)
提交回复
热议问题