TSQL拆分XML属性

时间:2012-11-19 03:31:05

标签: xml tsql

我有一个xml字符串,需要在sql中操作它。

<RuleData ReturnVariable="">
  <MateProperties>
    <Property Key="value" DisplayName="name value" />
    <Property Key="value2" DisplayName="name value2" />
  </MateProperties>
  <ReferenceNames>
    <Item Name="0" Value="=CouplerType + &quot;-1&quot;" />
    <Item Name="1" Value="Driveshaft-1" />
  </ReferenceNames>
  <ReferenceFeatures>
    *<Item Name="=CouplerType + &quot;-1&quot;" Value="CSYS_BOREB" />
    <Item Name="Driveshaft-1" Value="CSYS_CouplerINSIDE" />*
  </ReferenceFeatures>
</RuleData>

这两行我需要转换它们。

<Item Name="=CouplerType + &quot;-1&quot;" Value="CSYS_BOREB" />
<Item Name="Driveshaft-1" Value="CSYS_CouplerINSIDE" />

To这种新格式。

<Value>
  <Column Value="=CouplerType + &quot;" />
  <Column Value="CSYS_BOREB" />
</Value>
<Value>
  <Column Value="Driveshaft-1" />
  <Column Value="CSYS_CouplerINSIDE" />
</Value>

基本上每行必须分成两行并重新命名。我可以处理重新命名,我只是在拆分列时遇到问题。我还必须在ReferenceNames部分做同样的事情。那个更容易,因为它总是“0”和“1”所以我可以简单地将xml转换为字符串并找到替换它。但是,ReferenceFeatures部分更复杂,因为任何东西都可以在名称部分。

1 个答案:

答案 0 :(得分:0)

declare @xml xml =
    N'<RuleData>
        <ReferenceFeatures>
            <Item Name="=CouplerType + &quot;-1&quot;" Value="CSYS_BOREB" />
            <Item Name="Driveshaft-1" Value="CSYS_CouplerINSIDE" />
        </ReferenceFeatures>
    </RuleData>'

;with items as
(
    select
        row_number() over (order by (select 1)) as RowNumber
        ,t.n.value('@Name', 'nvarchar(255)') as Name
        ,t.n.value('@Value', 'nvarchar(255)') as Value
    from @xml.nodes('//RuleData/ReferenceFeatures/Item') as t(n)
)
select
    (select it.Name as [@Value] for xml path ('Column'), type),
    (select it.Value as [@Value] for xml path ('Column'), type)
from items it
order by it.RowNumber
for xml raw ('Value'), type