TSQL for xml add schema attribute to root node

My situation is (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

What gives me this XML:

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

Now I need to add the XML schema to the root directory of the node as follows:

<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 states that I must use WITH XMLNAMESPACES before the SELECT statement , but this does not work in my case.

How to add these xmlnames spaces?

+3
source share
2 answers

I found a solution to add all namespaces here:

fooobar.com/questions/1538101 / ...

It is clear that this is not a very “good” style, but in my case it works, and I have not yet found another working solution.

Decision

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]')

-- SOLUTION
SET @persons = replace(cast(@persons as varchar(max)), '<company>', '<company xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mydomain.com/xmlns/bla/blabla/myschema.xsd" xmlns="">')


SELECT @persons
+3
source

select, with xmlnamespaces .

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]')
+4

Source: https://habr.com/ru/post/1538090/


All Articles