I have a lot of XML documents in the app which are stored in the SQL Server database. Here is an example:
<para id="19" revDate="2022-05-04T04:00:00Z">
<emphasis>
<emphasis color="Blue">test</emphasis>
<emphasis color="Red">test</emphasis>
</emphasis>
<emphasis>
<emphasis color="Green">test</emphasis>
</emphasis>
</para>
I want to replace the values of color attributes for all emphasis and entry elements with the corresponding Hex color code. This is what i want to get:
<para id="19" revDate="2022-05-04T04:00:00Z">
<emphasis>
<emphasis color="0000FF">test</emphasis>
<emphasis color="FF0000">test</emphasis>
</emphasis>
<emphasis>
<emphasis color="008000">test</emphasis>
</emphasis>
</para>
So i will need some kind of switch/case. Note: attribute could have any hex value (not just red, green, blue):
DECLARE @ColorTextValue VARCHAR(20) = 'Blue'
DECLARE @ColorHexValue VARCHAR(6)
SET @ColorHexValue = CASE @ColorTextValue
WHEN 'Blue' THEN '0000FF'
WHEN 'Red' THEN 'FF0000'
WHEN 'Green' THEN '008000'
END
I have the following script right now:
DECLARE @tbl TABLE (XmlData XML);
INSERT INTO @tbl VALUES
('<para id="19" revDate="2022-05-04T04:00:00Z">
<emphasis>
<emphasis color="Blue">test</emphasis>
<emphasis color="Red">test</emphasis>
</emphasis>
<emphasis>
<emphasis color="Green">test</emphasis>
</emphasis>
</para>'
);
UPDATE
[XmlDocument]
SET
[XmlData].modify('replace value of (//*[self::emphasis or self::entry]/@color)[1] with "hexCodeHere"')
FROM
@tbl AS [XmlDocument]
WHERE
[XmlDocument].[XmlData].exist('//*[self::emphasis or self::entry][@color]') = 1
SELECT * FROM @tbl
As you can see it just has a hardcoded HexCode. How to add some kind of switch into this statement to calculate Hex code dynamically? Also it doesn't have a possibility to update ALL attributes. It updates only the first item