Convert Data Table to XML in SQL Server

Introduction

We can convert the data table into XML format using.  

  1. XML Raw 
  2. XML Path
  3. XML Auto 

Here I am going to use XML Raw to convert the data table to XML format.

1.XML Raw

RAW mode transforms each row in the query result into an XML element.

This is my table structure.

  

The query is to convert the data table to XML format. 

select*from Products for xml raw('Products'),root('ProductDetails')  

 Result

<ProductDetails>  
  <Products id="1" Name="T-shirts" Category="Mens Clothing" />  
  <Products id="2" Name="Track Suit" Category="Mens Clothing" />  
  <Products id="3" Name="Shoes" Category="Mens Footwear" />  
  <Products id="4" Name="Sandals" Category="Mens Footwear" />  
</ProductDetails>  

 2. XML Path

 The query is to convert the data table to XML format. 

select*from Products for xml path('Products'),root('ProductDetails')  

 Result   

<ProductDetails>  
  <Products>  
    <id>1</id>  
    <Name>T-shirts</Name>  
    <Category>Mens Clothing</Category>  
  </Products>  
  <Products>  
    <id>2</id>  
    <Name>Track Suit</Name>  
    <Category>Mens Clothing</Category>  
  </Products>  
  <Products>  
    <id>3</id>  
    <Name>Shoes</Name>  
    <Category>Mens Footwear</Category>  
  </Products>  
  <Products>  
    <id>4</id>  
    <Name>Sandals</Name>  
    <Category>Mens Footwear</Category>  
  </Products>  
</ProductDetails>

3. XML Auto

 The query is to convert the data table to XML format. 

select*from Products for xml auto,root('ProductDetails')  

Result 

<ProductDetails>  
  <Products id="1" Name="T-shirts" Category="Mens Clothing" />  
  <Products id="2" Name="Track Suit" Category="Mens Clothing" />  
  <Products id="3" Name="Shoes" Category="Mens Footwear" />  
  <Products id="4" Name="Sandals" Category="Mens Footwear" />  
</ProductDetails>  

Conclusion

From this blog, we taught how to convert the data table to XML using XML Raw, XML path, and XML Auto.

Next Recommended Reading Convert Varchar to Xml in Sql Server