Click here to Skip to main content
15,891,951 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have stored a svg image in SQL column. The column datatype is XML. The xml basically looks something like:
XML
<svg>
  <rect id="1">
    <rect id="in1" stroke="black"/>
    <circle id="in2" />
    <rect id="in3" stroke="black">
      <rect id="31" fill="Red"/>
    </rect>
    <circle id="in4"/>
  </rect>

 <g>
  <rect id="2">
    <circle>
     <rect id="in5">
  </rect>
 </g>
</svg>


How to loop through the xml in SQL so that I can find the correct <rect> tag with id 31 and change its fill color to "Blue"
Posted
Updated 9-Jul-15 21:37pm
v4
Comments
Anjali0904 21-Jul-15 5:42am    
Supposing the attribute is
<rect id="31" style="opacity:1;fill:#000fff;fill-stroke:#fffff"/>
</rect>
How do I change the value of fill now?

1 solution

You can use replace value of[^].

So something like the following:
SQL
DECLARE @data xml;
SET @data = '<svg>
  <rect id="1">
    <rect id="in1" stroke="black" />
    <circle id="in2" />
    <rect id="in3" stroke="black">
      <rect id="31" fill="Red" />
    </rect>
    <circle id="in4" />
  </rect>
 
 <g>
  <rect id="2">
    <circle>
     <rect id="in5" />
    </circle>
  </rect>
 </g>
</svg>';

SELECT @data;

SET @data.modify('
  replace value of (//rect[@id=("31")]/@fill)[1]
  with "blue"
');
SELECT @data;
 
Share this answer
 
Comments
Anjali0904 20-Jul-15 2:09am    
Hey Thanks Mika...
I have one more doubt. Is it possible to update multiple values at the same time...say change fill to blue of rect with id 31 and 32??
Wendelius 20-Jul-15 3:40am    
As far as I know you can't update multiple values at the same time. So you would need a loop of some kind. For example

DECLARE @counter int = 31

WHILE @counter <= 32 BEGIN
SET @data.modify('
replace value of (//rect[@id = (sql:variable("@counter"))]/@fill)[1]
with "blue"
');
SET @counter = @counter + 1
END
Anjali0904 21-Jul-15 2:05am    
Oh okk..Thanks once again Mika..
Wendelius 21-Jul-15 3:03am    
You're welcome :)
Anjali0904 21-Jul-15 6:03am    
Supposing the attribute is
<rect id="31" style="opacity:1;fill:#000fff;fill-stroke:#fffff"/>
</rect>
How do I change the value of fill now?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900