简体   繁体   English

重命名sql中的xml元素和属性

[英]Renaming xml elements and attributes in sql

I have a table, with a nvarchar(max) column that has some xml in it. 我有一个表,其中包含一些xml的nvarchar(max)列。

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 xml path select语句中重命名xml数据中的某些元素/属性,该语句从其他一些表中生成一些xml。

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: 将以以下格式返回xml:

<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: 但我希望xml是这样的:

<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 装箱起来对任何人来说都更容易,我将其放在sql小提琴中: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM