如何使用 FOR XML 从子元素中删除 xmlns

oll*_*lle 5 xml t-sql

我有一个用于生成 SOAP 文档的 TSQL 查询。我正在使用两个命名空间。即: - http://schemas.xmlsoap.org/soap/envelope/用于“打包”soap 文档 - 描述正文中包含的数据的自定义文档

目前,包括正文中的元素在内的每个元素都包含我不需要且想要的soapnamespace 引用,我只希望它位于根元素中。

所以我的 XML 现在看起来像

<soapenv:Envelope xmlns="soapenv" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:pas="foobar">
    <soapenv:Header xmlns="soapenv" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:pas="foobar" />
            <soapenv:Body xmlns="soapenv" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:pas="foobar">
                    <pas:SomeObject xmlns="soapenv" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:pas="foobar">
Run Code Online (Sandbox Code Playgroud)

我希望它看起来像

<soapenv:Envelope xmlns="soapenv" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:pas="foobar">
    <soapenv:Header/>
            <soapenv:Body>
                    <pas:SomeObject>
Run Code Online (Sandbox Code Playgroud)

在我当前使用的查询中

;WITH XMLNAMESPACES ( 'http://foobar' as pas,
      'http://schemas.xmlsoap.org/soap/envelope/' as soapenv
      )
SELECT (SELECT '' FOR XML PATH('soapenv:Header'),type ),
etc...
FOR XML PATH('soapenv:Envelope'), ELEMENTS
Run Code Online (Sandbox Code Playgroud)

Mik*_*son 5

对此连接项目进行投票以改变行为。

您可以使用for xml 显式来构建 XML。

像这样的东西:

;with DummyTable(id) as 
(
  select 1 union all
  select 2
)

select 1 as tag,
       0 as parent,
       'http://schemas.xmlsoap.org/soap/envelope/' as [soapenv:Envelope!1!xmlns:soapenv],
       'http://foobar' as [soapenv:Envelope!1!xmlns:pas],
        null as [pas:Child!2!pas:ID]
union all
select 2,
       1,
       null,
       null,
       id
from DummyTable       
for xml explicit
Run Code Online (Sandbox Code Playgroud)

结果:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:pas="http://foobar">
  <pas:Child pas:ID="1" />
  <pas:Child pas:ID="2" />
</soapenv:Envelope>
Run Code Online (Sandbox Code Playgroud)