这是我的源 xml 外观的示例
<Catalog xmlns="http://schemas.example.com/stuff/stuff">
<String Key="Name" Tag="22a41320-bb66-41a9-8806-760d13679c6c">Document Title 1</String>
<String Key="Name" Tag="023463cf-9237-45b6-ac3f-621b9b09f609">Title for document 2</String>
</Catalog>
我计划遍历 String 节点并将它们转换为 Document 节点(这仅显示循环的第一次迭代)。但是,当我插入新节点时,它会插入一个空的命名空间。这是我得到的结果:
<Catalog xmlns="http://schemas.example.com/stuff/stuff">
<String Key="Name" Tag="023463cf-9237-45b6-ac3f-621b9b09f609">Title for document 2</String>
<Document xmlns="" Key="Document Title 1" Handle="22a41320-bb66-41a9-8806-760d13679c6c" />
</Catalog>
注意空的命名空间。我想完全省略 Document 节点上的命名空间。
这是我想要的结果
<Catalog xmlns="http://schemas.example.com/stuff/stuff">
<String Key="Name" Tag="023463cf-9237-45b6-ac3f-621b9b09f609">Title for document 2</String>
<Document Key="Document Title 1" Handle="22a41320-bb66-41a9-8806-760d13679c6c" />
</Catalog>
这是您可以使用的完整查询:
declare @temp xml, @newNode xml;
set @temp = cast(
'<Catalog xmlns="http://schemas.example.com/stuff/stuff">
<String Key="Name" Tag="22a41320-bb66-41a9-8806-760d13679c6c">Document Title 1</String>
<String Key="Name" Tag="023463cf-9237-45b6-ac3f-621b9b09f609">Title for document 2</String>
</Catalog>' as xml)
select 'before', @temp
set @newNode = CAST(
'<Document Key="' + @temp.value('declare default element namespace "http://schemas.example.com/stuff/stuff"; (/Catalog/String/text())[1]', 'varchar(max)') +
'" Handle="' + @temp.value('declare default element namespace "http://schemas.example.com/stuff/stuff"; (/Catalog/String/@Tag)[1]', 'varchar(50)') + '" />'
as xml)
set @temp.modify('declare default element namespace "http://schemas.example.com/stuff/stuff"; insert sql:variable("@newNode") into (/Catalog)[1] ')
set @temp.modify('declare default element namespace "http://schemas.example.com/stuff/stuff"; delete (/Catalog/String)[1]')
select 'after', @temp