[英]Add an attribute to the root node
Please see the DDL below: 请参阅下面的DDL:
create table #Dataset1 (id int not null identity,firstname varchar(30),surname varchar(30), primary key (id))
insert into #Dataset1 (firstname,surname) values ('Mark','Williams')
And the SQL below: 以下SQL:
select firstname,surname
from #Dataset1
FOR XML PATH('Dataset1')
Which returns: 哪个回报:
<Dataset1>
<firstname>Mark</firstname>
<surname>Williams</surname>
</Dataset1>
How can I get the SQL to return: 如何让SQL返回:
<Dataset1 URN='1'>
<firstname>Mark</firstname>
<surname>Williams</surname>
</Dataset1>
URN=1 will be harcoded into the XML ie not generated from the database. URN = 1将被编码到XML中,即不是从数据库生成的。
Try this 尝试这个
SELECT
id AS [@URN]
,firstname
,surname
FROM #Dataset1
FOR XML PATH ('Dataset1')
Result 结果
<Dataset1 URN="1">
<firstname>Mark</firstname>
<surname>Williams</surname>
</Dataset1>
Your question is not all clear to me (especially your last sentence about hardcoded )... 你的问题对我来说并不是很清楚(特别是关于硬编码的最后一句话)......
Here are four different approaches: 以下是四种不同的方法:
If your will be hardcoded, ie not generated from the database means a fix value it should be this 如果您的硬编码,即不是从数据库生成意味着修复值应该是这个
SELECT 1 AS [@URN]
,firstname
,surname
FROM #Dataset1 FOR XML PATH('Dataset1');
If you want to add this as attribute to an existing XML you could do this 如果要将此属性添加到现有XML,则可以执行此操作
DECLARE @xml XML=
(
SELECT firstname
,surname
FROM #Dataset1 FOR XML PATH('Dataset1'),TYPE
);
SET @xml.modify('insert attribute URN {"1"} into (/Dataset1)[1]');
SELECT @xml;
If this should be added later you might do this on string level (but I would not advise this) 如果这应该稍后添加,你可以在字符串级别上执行此操作(但我不建议这样做)
DECLARE @xml XML=
(
SELECT firstname
,surname
FROM #Dataset1 FOR XML PATH('Dataset1'),TYPE
);
SET @xml=
CAST
(
REPLACE
(
CAST(@xml AS NVARCHAR(MAX))
,N'<Dataset1>',N'<Dataset1 URN="1">')
AS XML);
SELECT @xml;
All three will return as 这三个人都将返回
<Dataset1 URN="1">
<firstname>Mark</firstname>
<surname>Williams</surname>
</Dataset1>
If your "URN" is a namespace actually 如果您的“URN”实际上是名称空间
WITH XMLNAMESPACES(DEFAULT 'SomeDefault'
,'SomeOther' AS URN)
SELECT firstname
,surname
FROM #Dataset1 FOR XML PATH('Dataset1')
The result would be this 结果就是这样
<Dataset1 xmlns:URN="SomeOther" xmlns="SomeDefault">
<firstname>Mark</firstname>
<surname>Williams</surname>
</Dataset1>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.