2012-11-28 44 views
0

更新屬性值,我有以下XML取決於條件XML使用XQuery

<Root xmlns:test="http://sample"> 
    <Values> 
     <Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance" d3p1:type="1"> 
     </Value> 
     <Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance" d3p1:type="1"> 
     </Value> 
     <Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance" d3p1:type="2"> 
     </Value> 
     <Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance" d3p1:type="2"> 
     </Value> 
     <Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance" d3p1:type="1"> 
     </Value> 
    </Values> 
</Root> 

在這裏,我想用type=2所有元素值更新爲type = 3

請有人可以告訴我如何做到這一點?

回答

2
declare @XML xml = 
'<Root xmlns:test="http://sample"> 
    <Values> 
    <Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance" d3p1:type="1"></Value> 
    <Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance" d3p1:type="1"></Value> 
    <Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance" d3p1:type="2"></Value> 
    <Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance" d3p1:type="2"></Value> 
    <Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance" d3p1:type="1"></Value> 
    </Values> 
</Root>'; 

while @XML.exist('declare namespace d3p1="http://www.w3.org/2001/XMLSchema-instance"; 
        /Root/Values/Value[@d3p1:type = "1"]') = 1 
begin 
    set @XML.modify('declare namespace d3p1="http://www.w3.org/2001/XMLSchema-instance"; 
        replace value of (/Root/Values/Value[@d3p1:type="1"]/@d3p1:type)[1] 
        with 2') 
end 

select @XML 

結果:

<Root xmlns:test="http://sample"> 
    <Values> 
    <Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance" d3p1:type="2" /> 
    <Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance" d3p1:type="2" /> 
    <Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance" d3p1:type="2" /> 
    <Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance" d3p1:type="2" /> 
    <Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance" d3p1:type="2" /> 
    </Values> 
</Root> 
+0

由於它的工作:) –