Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent XML-DML modify function adding empty namespaces to the inserting nodes

So basically I have a script that updates XML based on whether such node exists or not. Here's the t-sql

DECLARE @newJob XML
SET @newJob = N'<job>
    <job-detail>
      <name>job-name</name>
    </job-detail>
  </job>'

;WITH XMLNAMESPACES(DEFAULT 'http://quartznet.sourceforge.net/JobSchedulingData')
UPDATE XmlTable
SET ConfigXml.modify('
insert sql:variable("@newJob") 
as last into (/quartz)[1]')
WHERE ConfigXml.exist(N'//quartz/job/job-detail/name[.="job-name"]') = 0

Now everything works as expected except only the inserted node now contains empty namespace like this

<job xmlns="">

If I remove

;WITH XMLNAMESPACES(DEFAULT 'http://quartznet.sourceforge.net/JobSchedulingData')

query stops executing. I think this is because my root node has namespaces defined

<quartz xmlns="http://quartznet.sourceforge.net/JobSchedulingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0" overwrite-existing-jobs="true">

So my question is - is there any way to prevent this namespace addition to the node that is being inserted?

like image 372
Mike Avatar asked Oct 02 '22 13:10

Mike


1 Answers

To overcome this problem I slightly changed the approach, in particular I'm declaring xml namespaces in xml-dml modify function itself, and adding namespace prefixes to the inserting nodes. That did the trick

UPDATE XmlTable
SET ConfigXml.modify('
declare namespace ns="http://quartznet.sourceforge.net/JobSchedulingData";
insert <ns:job>
    <ns:job-detail>
      <ns:name>jobName</ns:name>
    </ns:job-detail>
  </ns:job>
as last into (/ns:quartz)[1]')
WHERE ConfigXml.exist(N'
declare namespace ns="http://quartznet.sourceforge.net/JobSchedulingData";
//ns:quartz/ns:job/ns:job-detail/ns:name[.="jobName"]') = 0

Hope this helps someone else.

like image 108
Mike Avatar answered Oct 07 '22 16:10

Mike