user979331
user979331

Reputation: 11861

SQL XML add elements to root

I have an XML that is being generated via SQL and the root looks like this:

<ArrayOfKeyValueOfstringPunchListCellModel84zsBx89 
      ns1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">

I want it to look like so:

<ArrayOfKeyValueOfstringPunchListCellModel84zsBx89 
      xmlns:i="http://www.w3.org/2001/XMLSchema-instance" 
      xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">

Here is my SQL code:

DECLARE @persons XML = (
SELECT(
blah blah blah
)FOR XML PATH(''), ROOT('ArrayOfKeyValueOfstringPunchListCellModel84zsBx89'))
set @persons.modify('insert ( attribute ns1 {"http://schemas.microsoft.com/2003/10/Serialization/Arrays"}) into (/ArrayOfKeyValueOfstringPunchListCellModel84zsBx89)[1]')
    SELECT @persons

and it returns the first root, how do I get it return like the second root I showed?

Upvotes: 0

Views: 67

Answers (1)

Gottfried Lesigang
Gottfried Lesigang

Reputation: 67301

You need to declare the namespaces using WITH XMLNAMESPACES

Try this:

WITH XMLNAMESPACES('http://www.w3.org/2001/XMLSchema-instance' AS i
                  ,DEFAULT 'http://schemas.microsoft.com/2003/10/Serialization/Arrays')
SELECT NULL
FOR XML PATH('ArrayOfKeyValueOfstringPunchListCellModel84zsBx89')

The result

<ArrayOfKeyValueOfstringPunchListCellModel84zsBx89 xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" />

Upvotes: 3

Related Questions