[英]Renaming xml elements and attributes in sql
我有一个表,其中包含一些xml的nvarchar(max)列。
例如:
Create table ta_test (xmlstring varchar(max), otherData varchar(10))
insert into ta_test values
('<items><item attr1="1" attr2="2"/><item attr1="1" attr2="2"><subitem attr1="1"/></item></items>','test1'),
('<items><item attr1="1" attr2="2"/><item attr1="1" attr2="2"><subitem attr1="1"/></item></items>','test2'),
('<items><item attr1="1" attr2="2"/><item attr1="1" attr2="2"><subitem attr1="1"/><subitem attr1="1"/></item></items>','test3')
我想从for xml path
select语句中重命名xml数据中的某些元素/属性,该语句从其他一些表中生成一些xml。
例如:
select
otherdata as '@OtherData',
cast(xmlstring as xml)
from ta_test
for xml path ('test'), type
将以以下格式返回xml:
<test OtherData="test1">
<items>
<item attr1="1" attr2="2"/>
<item attr1="1" attr2="2">
<subitem attr1="1"/>
</item>
</items>
</test>
但我希望xml是这样的:
<test OtherData="test2">
<NewItemsNodeName>
<NewItemNodeName NewAttr1Name="1" NewAttr2Name="2"/>
<NewItemNodeName NewAttr1Name="1" NewAttr2Name="2">
<subitem NewAttr1Name="1"/>
</NewItemNodeName>
</NewItemsNodeName>
</test>
我一直在尝试通过交叉连接来完成此操作,但是我一直无法使其正常工作,而且我也不知道我是否正从正确的角度着手。
装箱起来对任何人来说都更容易,我将其放在sql小提琴中: http ://sqlfiddle.com/#!3/fd77c/3/0
有人可以帮忙吗?
select T1.otherData as '@OtherData',
(
select I.X.value('@attr1', 'int') as '@NewAttr1Name',
I.X.value('@attr2', 'int') as '@NewAttr2Name',
(
select S.X.value('@attr1', 'int') as '@NewAttrName1'
from I.X.nodes('subitem') as S(X)
for xml path('subitem'), type
)
from T2.X.nodes('/items/item') as I(X)
for xml path('NewItemNodeName'), root('NewItemsNodeName'), type
)
from ta_test as T1
cross apply (select cast(T1.xmlstring as xml).query('.')) as T2(X)
for xml path('test'), type
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.