SQL XML 添加元素到根

SQL XML add elements to root

我有一个 XML 是通过 SQL 生成的,根看起来像这样:

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

我希望它看起来像这样:

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

这是我的 SQL 代码:

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

而且它 return 是第一个根,我如何得到它 return 就像我显示的第二个根一样?

您需要使用 WITH XMLNAMESPACES

声明命名空间

试试这个:

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')

结果

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