Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL for xml add schema attribute to root node

My situation is this (simplified):

DECLARE @period XML = (
SELECT
'2012' 'period'
FOR XML PATH(''), ROOT ('survey'))

DECLARE @persons XML = (
SELECT
Person.Name 'users/person'
FROM Person
FOR XML PATH(''), ROOT ('company'))

SET @persons.modify('insert sql:variable("@period") as first into (/company)[1]')
SELECT @persons

Which gives me a XML like this:

<company>
  <survey>
    <period>2012</period>
  </survey>
  <users>
    <person>Dubach</person>
  </users>
  <users>
    <person>Pletscher</person>
  </users>
  ...

Now I need to add a XML-schema to the root node like this:

<company xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mydomain.com/xmlns/bla/blabla/myschema.xsd" xmlns="http://www.mydomain.com/xmlns/bla/blabla">
  <survey>
    <period>2012</period>
  </survey>
  <users>
    <person>Dubach</person>
  </users>
  <users>
    <person>Pletscher</person>
  </users>
  ...

Microsoft says I have to use WITH XMLNAMESPACES before the SELECT statement but that does not work in my case.

How can I add these xmlnamespaces?

like image 818
Bruno Bieri Avatar asked Mar 15 '26 00:03

Bruno Bieri


1 Answers

Split the declare from the select, then use with xmlnamespaces as described.

DECLARE @persons XML 

;with xmlnamespaces (
    'http://www.mydomain.com/xmlns/bla/blabla' as ns,
    'http://www.w3.org/2001/XMLSchema-instance' as xsi
)
select @persons = (
    select
        Person.Name as 'ns:users/person' 
        FROM Person 
    FOR XML PATH(''), ROOT ('company')
)

set @persons.modify('insert ( attribute xsi:schemaLocation {"http://www.mydomain.com/xmlns/bla/blabla/myschema.xsd"}) into (/company)[1]')
like image 181
podiluska Avatar answered Mar 17 '26 14:03

podiluska



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!