0

I am trying to modify the attribute of an XML root attribute in XQuery with T-SQL but I don't manage to do that. My XML has a namespace in it and I can't exactly bypass this. When I query the value of the xml I successfully retrieve the value because I use: ;WITH XMLNAMESPACES (DEFAULT 'some:namespace:here:v1'). I also tried to use: 'declare default element namespace "some:namespace:here:v1";' in the XQuery but does not seem to work.

Any ideas of how can I achieve this ?

This is an example of the XML I am trying to modify.

DECLARE @XML_TO_READ XML = N'
    <F2101 xmlns="some:namespace:here:v1" propertyToModify="valueToModify">
        <person xmlns="some:namespace:here:v1" anotherPropertyToModify="anotherValueToModify" />
    </F2101>'

I retrieve the value like this:

    ;WITH XMLNAMESPACES (DEFAULT 'some:namespace:here:v1')
    SELECT propertyToModify = 
@XML_TO_READ.value('(/F2101/@propertyToModify)[1]', 'nvarchar(50)')

And I tried to modify (update) the value like this:

SET @XML_TO_READ.modify('
    declare default element namespace "some:namespace:here:v1";
    replace value of (/F2101/propertyToModify/text())[1] with ("modifiedValue")')

I tried multiple solutions but I did not find anything that would work for my special case here.

Thanks in advance.

R3muSGFX
  • 63
  • 4
  • 12

1 Answers1

2

Your statement should be:

SET @XML_TO_READ.modify('
declare default element namespace "some:namespace:here:v1";
replace value of (/F2101/@propertyToModify)[1] with ("modifiedValue")')

Note the "@propertyToModify" rather than "propertyToModify/text()".

Also, documentation link: replace value of (XML DML).

Anssssss
  • 3,087
  • 31
  • 40
  • Worked like a charm. Thank you for this response. I did read the documentation of the replace but didn't know where I was wrong... – R3muSGFX Jul 23 '19 at 14:59