问题
My MS SQL table has following data
ID CONTENT FLAG TEXT
----------------------------------
1 content1 T text1
2 content2 F text2
3 content3 T text2
and i want to select values from this table in below format without any root node.
<ADDRESS ID="1" FLAG="T">
<FORM CONTENT="content1" TEXT="text1"/>
</ADDRESS>
<ADDRESS ID="2" FLAG="F">
<FORM CONTENT="content2" TEXT="text2"/>
</ADDRESS>
<ADDRESS ID="3" FLAG="T">
<FORM CONTENT="content3" TEXT="text3"/>
</ADDRESS>
回答1:
This is quite a while ago, but - just in case you're still interested in a solution - this would be the query:
DECLARE @tbl TABLE(ID INT,CONTENT VARCHAR(100),FLAG VARCHAR(1),TEXT VARCHAR(100));
INSERT INTO @tbl VALUES
(1,'content1','T','text1')
,(2,'content2','F','text2')
,(3,'content3','T','text2');
SELECT tbl.ID AS [@ID]
,tbl.FLAG AS [@FLAG]
,tbl.CONTENT AS [Form/@CONTENT]
,tbl.TEXT AS [Form/@Text]
FROM @tbl AS tbl
FOR XML PATH('ADDRESS') /*,ROOT('Root')*/ --add Root if you need it
The Result
<ADDRESS ID="1" FLAG="T">
<Form CONTENT="content1" Text="text1" />
</ADDRESS>
<ADDRESS ID="2" FLAG="F">
<Form CONTENT="content2" Text="text2" />
</ADDRESS>
<ADDRESS ID="3" FLAG="T">
<Form CONTENT="content3" Text="text2" />
</ADDRESS>
来源:https://stackoverflow.com/questions/33149049/convert-sql-table-to-xml-with-2-node-for-each-row