我试图生成以下格式的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>
我尝试了所有可能性,但没有获得标签。谁能帮我解决这个问题。
我无法从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的修复程序。