I have a table, with a nvarchar(max) column that has some xml in it.
For example:
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')
I would like to rename some of the elements/attributes from the xml data from within a for xml path
select statement that is generating some xml from some other tables.
For example:
select
otherdata as '@OtherData',
cast(xmlstring as xml)
from ta_test
for xml path ('test'), type
Would return xml in the format of:
<test OtherData="test1">
<items>
<item attr1="1" attr2="2"/>
<item attr1="1" attr2="2">
<subitem attr1="1"/>
</item>
</items>
</test>
But I would like the xml to be something like:
<test OtherData="test2">
<NewItemsNodeName>
<NewItemNodeName NewAttr1Name="1" NewAttr2Name="2"/>
<NewItemNodeName NewAttr1Name="1" NewAttr2Name="2">
<subitem NewAttr1Name="1"/>
</NewItemNodeName>
</NewItemsNodeName>
</test>
I've been trying to do this unsuccessfully with a cross join, I've not been able to get it to work, and I don't know if I'm approaching it from the right angle.
Encase it makes it easier for anybody, I've put this in an sql fiddle: http://sqlfiddle.com/#!3/fd77c/3/0
Can anybody help?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.