【发布时间】:2017-04-04 16:22:54
【问题描述】:
我正在尝试在 SQL Server 2014 的 XML 根元素中添加 xmlns MsgDtTm 和 MessageIdattributes。我正在尝试这个:
declare @TEMP table (ID nvarchar(max), Name nvarchar(max))
declare @count int =0
WHILE @count < 4
BEGIN
declare @name nvarchar(20),@id nvarchar(max)
select @name= SUBSTRING(CONVERT(varchar(255), NEWID()), 0, 7)
,@id= CHAR(ROUND(RAND() * 93 + 33, 0))
insert into @TEMP values(@id,@name)
set @count= @count +1
END
declare @msgId nvarchaR(24)
SET @msgId='11EXP'+REPLACE(convert(varchar(10),getdate(),103),'/','')+'1'
DECLARE @Xml xml
SET @Xml = (select * from @TEMP for xml path('DefaultName'), type)
;WITH XMLNAMESPACES (DEFAULT 'http://abc.go.com')
select GETDATE() as "@MsgDtTm"
,@msgId as "@MessageId"
,--'http://abc.go.com' as "@xmlns",
@Xml for xml path('Person')
得到这个结果
<Person xmlns="http://abc.go.com" MsgDtTm="2016-11-21T15:13:10.440" MessageId="11EXP211120161">
<DefaultName xmlns="">
<ID>y</ID>
<Name>7BDCB6</Name>
</DefaultName>
<DefaultName xmlns="">
<ID>2</ID>
<Name>F8E997</Name>
</DefaultName>
<DefaultName xmlns="">
<ID>"</ID>
<Name>01E71C</Name>
</DefaultName>
<DefaultName xmlns="">
<ID>k</ID>
<Name>E4059A</Name>
</DefaultName>
</Person>
我在Default 元素中得到了空白的xmlns 属性。我想要xmlns 中的Person 元素而不是Default 元素。我的预期结果如下:
<Person xmlns="http://abc.go.com" MsgDtTm="2016-11-21T15:13:10.440" MessageId="11EXP211120161">
<DefaultName>
<ID>y</ID>
<Name>7BDCB6</Name>
</DefaultName>
<DefaultName>
<ID>2</ID>
<Name>F8E997</Name>
</DefaultName>
<DefaultName>
<ID>"</ID>
<Name>01E71C</Name>
</DefaultName>
<DefaultName>
<ID>k</ID>
<Name>E4059A</Name>
</DefaultName>
</Person>
如果我使用;WITH XMLNAMESPACES ('http://abc.go.com' as f),那么它将在根目录下,但结果我会得到xmlns:f="..."。我不想追加:objectOfXMLNAMESPACES,我只想要xmlns。
【问题讨论】:
标签: sql sql-server xml sql-server-2008-r2 sql-server-2014