我在变量@xml
中有一个类似下面的xml<ContentTemplate>
<Tab Title="Lesson">
<Section Title="Lesson Opening" />
<Section Title="Lesson/Activity" />
</Tab>
<Tab Title="Wrap Up and Assessment">
<Section Title="Lesson Closing" />
<Section Title="Tracking Progress/Daily Assessment" />
</Tab>
<Tab Title="Differentiated Instruction">
<Section Title="Strategies - Keyword" />
<Section Title="Strategies – Text" />
<Section Title="Resources" />
<Section Title="Acceleration/Enrichment" />
</Tab>
<Tab Title="District Resources">
<Section Title="Related Content Items" />
<Section Title="Other" />
</Tab>
</ContentTemplate>
我想在上面的xml中为所有标签节点插入一个属性。 输出应如下所示:
<ContentTemplate>
<Tab Title="Lesson" PortletName="CommunitiesViewer">
<Section Title="Lesson Opening" />
<Section Title="Lesson/Activity" />
</Tab>
<Tab Title="Wrap Up and Assessment" PortletName="CommunitiesViewer">
<Section Title="Lesson Closing" />
<Section Title="Tracking Progress/Daily Assessment" />
</Tab>
<Tab Title="Differentiated Instruction" PortletName="CommunitiesViewer">
<Section Title="Strategies - Keyword" />
<Section Title="Strategies – Text" />
<Section Title="Resources" />
<Section Title="Acceleration/Enrichment" />
</Tab>
<Tab Title="District Resources" PortletName="CommunitiesViewer">
<Section Title="Related Content Items" />
<Section Title="Other" />
</Tab>
</ContentTemplate>
我尝试了以下代码来获取上面的xml
set @xml.modify( 'insert attribute PortletName {sql:variable("@PortletName")} into (ContentTemplate/Tab)[1]')
它只是更新第一个子节点。
如何更新xml的所有子节点..
提前致谢
答案 0 :(得分:2)
您在变量中的XML
DECLARE @xml XML=
N'<ContentTemplate>
<Tab Title="Lesson">
<Section Title="Lesson Opening" />
<Section Title="Lesson/Activity" />
</Tab>
<Tab Title="Wrap Up and Assessment">
<Section Title="Lesson Closing" />
<Section Title="Tracking Progress/Daily Assessment" />
</Tab>
<Tab Title="Differentiated Instruction">
<Section Title="Strategies - Keyword" />
<Section Title="Strategies – Text" />
<Section Title="Resources" />
<Section Title="Acceleration/Enrichment" />
</Tab>
<Tab Title="District Resources">
<Section Title="Related Content Items" />
<Section Title="Other" />
</Tab>
</ContentTemplate>';
.modify()
- 语句允许您更改XML中的一个体面点,但您需要多次调用才能更改许多地方。 FLWOR允许您自行重新构建XML:
SET @xml=@xml.query(
'<ContentTemplate>
{
for $t in /ContentTemplate/Tab
return
<Tab Title="{$t/@Title}" PortletName="CommunitiesViewer">
{$t/*}
</Tab>
}
</ContentTemplate>');
SELECT @xml
SELECT ... FOR XML PATH()
您可以通过这种方法达到相同的目标:重新构建XML,但这次它被粉碎并用作新的SELECT ... FOR XML PATH
SELECT tb.value('@Title','nvarchar(max)') AS [@Title]
,'CommunitiesViewer' AS [@PortletName]
,tb.query('*')
FROM @xml.nodes('/ContentTemplate/Tab') AS A(tb)
FOR XML PATH('Tab'),ROOT('ContentTemplate')