简体   繁体   中英

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?

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

I found a solution to add all the namespaces here:

https://stackoverflow.com/a/536781/1306012

Obvious it's not very "nice" style but in my case it works and I haven't found another working solution yet.

SOLUTION

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM