2011-09-29 92 views
0

我想要替换XML中属性的值。该属性在xml中多次出现。我怎么能代替这些一次性SQL Server XML替换属性中的值

我的XML lools一些什么样的如下:

<Example> 
    <A> 
    <B Type = "x">qqq</B> 
    <B Type = "x">www</B> 
    </A> 
    <C> 
    <D Type = "x">aaa</D> 
    <D Type = "x">uuu</D> 
    </C> 
</Example> 

我想Ÿ

回答

1

全部更换x你不能代替一次性使用replace value of (XML DML)。你必须循环做。

declare @xml xml = ' 
<Example> 
    <A> 
    <B Type = "x">qqq</B> 
    <B Type = "x">www</B> 
    </A> 
    <C> 
    <D Type = "x">aaa</D> 
    <D Type = "x">uuu</D> 
    </C> 
</Example> 
' 

while (select @xml.exist('//*[@Type = "x"]')) = 1 
begin 
    set @xml.modify('replace value of (//*[@Type = "x"]/@Type)[1] with "y"') 
end 

select @xml 

结果:

<Example> 
    <A> 
    <B Type="y">qqq</B> 
    <B Type="y">www</B> 
    </A> 
    <C> 
    <D Type="y">aaa</D> 
    <D Type="y">uuu</D> 
    </C> 
</Example> 

更新

替换值X和Z与Y:

while (select @xml.exist('//*[@Type = ("x","z")]')) = 1 
begin 
    set @xml.modify('replace value of (//*[@Type = ("x","z")]/@Type)[1] with "y"') 
end 

,其中y替换所有值:

while (select @xml.exist('//*[@Type != "y"]')) = 1 
begin 
    set @xml.modify('replace value of (//*[@Type != "y"]/@Type)[1] with "y"') 
end 
+0

嗨Mikael,谢谢你的答案,这很好,但我在这里有另一个问题,在每个元素的类型属性是不同的,例如在整个元素A,它是X和整个Elemnt B它是Z和我必须用y代替所有z和x ..我怎么能这样做... – Santy

+0

@Santy - 用一些替代方案更新了答案。 –