2

给定以下尝试构造 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>
4

2 回答 2

3

我认为你可以这样做:

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中,您可以找到通配符作为列名的文档。

于 2015-04-28T20:55:14.313 回答
1

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

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 语法相结合,因此现在要解释诸如未命名元素之类的重载概念并不总是那么容易.

于 2015-04-28T17:02:29.667 回答