Convert Data Table to XML in SQL Server

We can convert the data table into the XML format using  
  1. XML Raw 
  2. XML Path
  3. XML Auto 
Here I am going to use the XML Raw to convert the data table to XML format
 
1.XML Raw
 
RAW mode transform each row in the query result into an XML element 
This is my table structure
 
  
The query to convert data table to XML format. 
  1. select*from Products for xml raw('Products'),root('ProductDetails')  
 Result: 
  1. <ProductDetails>  
  2.   <Products id="1" Name="T-shirts" Category="Mens Clothing" />  
  3.   <Products id="2" Name="Track Suit" Category="Mens Clothing" />  
  4.   <Products id="3" Name="Shoes" Category="Mens Footwear" />  
  5.   <Products id="4" Name="Sandals" Category="Mens Footwear" />  
  6. </ProductDetails>  
 2. XML Path
 
 Query 
  1. select*from Products for xml path('Products'),root('ProductDetails')  
 Result 
  1. <ProductDetails>  
  2.   <Products>  
  3.     <id>1</id>  
  4.     <Name>T-shirts</Name>  
  5.     <Category>Mens Clothing</Category>  
  6.   </Products>  
  7.   <Products>  
  8.     <id>2</id>  
  9.     <Name>Track Suit</Name>  
  10.     <Category>Mens Clothing</Category>  
  11.   </Products>  
  12.   <Products>  
  13.     <id>3</id>  
  14.     <Name>Shoes</Name>  
  15.     <Category>Mens Footwear</Category>  
  16.   </Products>  
  17.   <Products>  
  18.     <id>4</id>  
  19.     <Name>Sandals</Name>  
  20.     <Category>Mens Footwear</Category>  
  21.   </Products>  
  22. </ProductDetails>  
3. XML Auto
 
Query 
  1. select*from Products for xml auto,root('ProductDetails')  
Result 
  1. <ProductDetails>  
  2.   <Products id="1" Name="T-shirts" Category="Mens Clothing" />  
  3.   <Products id="2" Name="Track Suit" Category="Mens Clothing" />  
  4.   <Products id="3" Name="Shoes" Category="Mens Footwear" />  
  5.   <Products id="4" Name="Sandals" Category="Mens Footwear" />  
  6. </ProductDetails>  
Ebook Download
View all
Learn
View all