TSQL for xml将架构属性添加到根节点

时间:2012-10-04 11:38:10

标签: sql-server xml tsql root

我的情况是这样的(简化):

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

这给了我这样的XML:

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

现在我需要将XML模式添加到根节点,如下所示:

<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>
  ...
在SELECT语句之前

Microsoft says I have to use WITH XMLNAMESPACES但在我的情况下不起作用。

如何添加这些xmlnamespaces?

2 个答案:

答案 0 :(得分:4)

从选择中拆分声明,然后将with xmlnamespaces用作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]')

答案 1 :(得分:3)

我找到了一个在这里添加所有命名空间的解决方案:

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

显然它不是非常“漂亮”的风格,但在我的情况下,它有效,我还没有找到另一个有效的解决方案。

<强>解

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