【问题标题】:SQL XML add elements to rootSQL XML 将元素添加到根
【发布时间】:2016-04-25 20:29:27
【问题描述】:

我有一个通过 SQL 生成的 XML,其根目录如下所示:

<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

它返回第一个根,我如何让它像我展示的第二个根一样返回?

【问题讨论】:

    标签: sql sql-server xml tsql xml-namespaces


    【解决方案1】:

    您需要使用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" />
    

    【讨论】:

    • 但这会为我的所有节点添加属性
    • @user979331 你是对的。这是多年来众所周知的问题......这不是错误,但很烦人。甚至还有Connect-article。有几种解决方法......如果你显示你的查询(部分,写在哪里 blah blah blah,我可以进一步帮助你......我建议 - 因为这个答案完全解决了当前问题, 投票并接受它。然后开始一个新问题我如何避免重复命名空间? 我很快就会在那里弹出。
    猜你喜欢
    • 1970-01-01
    • 2019-10-14
    • 2013-03-16
    • 2012-04-14
    • 2013-07-19
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多