2012-09-27 120 views
2

我嘗試生成以下格式的XML:如何生成元素的XML和屬性使用XML明確

<Root> 
    <Domain>Abc</Domain> 
    <Name>Xyz</Name> 
    <Contents> 
     <Content> 
      <ID>1</ID> 
      <Value>Test 1</Value> 
      <Record ID="1">Test 1</Record> 
     </Content> 
     <Content> 
      <ID>2</ID> 
      <Value>Test 2</Value> 
      <Record ID="2">Test 2</Record> 
     </Content> 
    </Contents> 
</Root> 

我的查詢如下:

declare @TestTable table (ID int, Value varchar(100)) 

insert into @TestTable values (1,'Test 1') 
insert into @TestTable values (2,'Test 2') 

declare @Domain varchar(max)='Abc' 
declare @Name varchar(max)='Xyz' 

SELECT 
1 AS Tag, 
NULL AS Parent, 
@Domain as 'Root!1!Domain!Element', 
@Name as 'Root!1!Name!Element', 
NULL as 'Contents!2!Element', 
NULL as 'Content!3!ID!Element', 
NULL as 'Content!3!Value!Element', 
NULL as 'Content!3!Record!Element' 

union 

SELECT 
2 AS Tag, 
1 AS Parent, 
NULL,NULL,NULL,NULL,NULL,NULL 

union 

select 
3 as Tag, 
2 as Parent, 
NUll,NUll,NULL, 
ID,Value,Value 
from @TestTable 

FOR XML EXPLICIT 

我查詢不產生記錄標籤完全,它是目前

<Record>Test 2</Record> 

這應該是作爲

<Record ID=2>Test 2</Record> 

我試過所有的可能性,但沒有得到標籤。任何人都可以幫助我解決這個問題。

回答

0

我無法從xml獲得預期的輸出顯式,而是我使用xml路徑並獲得了輸出。這是我更新的查詢

SELECT 
     @Domain "Domain", 
     @Name "Name", 
(
SELECT 
     ID "ID", 
     Value "Value", 
     (select 
     ID "@ID", 
     Value as "text()"  
     FOR XML PATH('Record'), ELEMENTS, TYPE)  
FROM @TestTable 
FOR XML PATH ('Content'), TYPE, ROOT('Contents') 
) 
FOR XML PATH ('Root') 

歡迎您發佈使用xml explicit的修復程序。

0

使用FOR XML EXPLICIT時不要忘記ORDER BY。


SELECT 
    1 AS Tag, 
    NULL AS Parent, 
    @Domain as 'Root!1!Domain!Element', 
    @Name as 'Root!1!Name!Element', 
    NULL as 'Contents!2!Element', 
    NULL as 'Content!3!ID!Element', 
    NULL as 'Content!3!Value!Element', 
    NULL as 'Record!4!ID', 
    NULL as 'Record!4!' 

union 

SELECT 
    2 AS Tag, 
    1 AS Parent, 
    @Domain,NULL,NULL,NULL,NULL,NULL, null 

union 

select 
    3 as Tag, 
    2 as Parent, 
    @Domain,NUll,NULL, 
    ID,Value,null,null 

    from @TestTable 
union 

select 
    4 as Tag, 
    3 as Parent, 
    @Domain,NUll,NULL, 
    ID,Value,ID,Value 

    from @TestTable 
ORDER BY 'Root!1!Domain!Element','Contents!2!Element','Content!3!ID!Element','Record!4!ID' 

FOR XML EXPLICIT