0

I have the following 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>

Here I am trying to update all value elements with type=2 to type = 3.

Please can somebody tell me how this can be done?

1 Answer 1

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

Result:

<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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.