如何在 SQL Server 中的 XML 投影中输出原始 xml,而无需引入额外的 xml 根元素



给定以下尝试构造XML的T-SQL代码段。

declare @table table
(
    col1 varchar(max),
    col2 varchar(max),
    col3 xml
)
declare @someXml xml = '
<innerRoot a="b">
    <child>1</child>
    <child>2</child>
    <child>3</child>
</innerRoot>
'
insert into @table values ('VALUE1', 'VALUE2', @someXml)
select 
    t.col1 as '@attribute1',
    t.col2 as '@attribute2',
    t.col3 as UnwantedElement
from @table as t
for xml path('Root'), type

生成的 XML 是:

<Root attribute1="VALUE1" attribute2="VALUE2">
  <UnwantedElement>
    <innerRoot a="b">
      <child>1</child>
      <child>2</child>
      <child>3</child>
    </innerRoot>
  </UnwantedElement>
</Root>

如何在没有 UnwantedElement 的情况下获得相同的输出,使其看起来像下面的示例。

<Root attribute1="VALUE1" attribute2="VALUE2">
  <innerRoot a="b">
    <child>1</child>
    <child>2</child>
    <child>3</child>
  </innerRoot>
</Root>
我认为

你可以这样做:

declare @table table
(
    col1 varchar(max),
    col2 varchar(max),
    col3 xml
)
declare @someXml xml = '
<innerRoot a="b">
    <child>1</child>
    <child>2</child>
    <child>3</child>
</innerRoot>
'
insert into @table values ('VALUE1', 'VALUE2', @someXml)
select 
    t.col1 as '@attribute1',
    t.col2 as '@attribute2',
    t.col3 as [*]
from @table as t
for xml path('Root'), type

在这里,msdn 可以找到通配符作为列名的文档。

经过一些实验后,我想出的解决方案是使用查询方法作为一种无操作来避免自动命名。

select 
    t.col1 as '@attribute1',
    t.col2 as '@attribute2',
    t.col3.query('/')
from @table as t
for xml path('Root')

导致我这样做的概念是查询innerRoot和元素上的所有属性。但是,在我的实验中,我注意到在指定查询时,col3 名称不再用作名称。


我对SQL Server中的XML的一个抱怨是语法如何与许多开发人员(如我)习惯的传统SQL语法相结合,因此现在并不总是那么容易解释诸如未命名元素之类的重载概念。

最新更新