Create XML Files using Linq
August 1, 2012
In one my previous blog posts, I had briefly touched upon XSD to create XML files. LINQ offers a similar, yet much faster feature to create XML files.
Here’s how you can quickly create an XML file from a database table.
The database table is created in a database named Movies on my SQLServer Express database. It has two columns MovieId and Title.
using System; using System.Data; using System.Data.SqlClient; using System.Xml.Linq; namespace XMLFileCreator { class XmlCreator { private static SqlConnection _sqlConn; static void Main() { DbConnect(); CreateXml(FetchRecords()); _sqlConn.Close(); } static DataTable FetchRecords() { const string sqlStr = "SELECT * FROM Movies"; var sqlCommand = new SqlCommand() { Connection = _sqlConn, CommandText = sqlStr, CommandType = CommandType.Text }; var adapter = new SqlDataAdapter(sqlCommand); var dt = new DataTable(); adapter.Fill(dt); Console.WriteLine(String.Format("No of Movie Titles:\t{0}", dt.Rows.Count)); return dt; } static void DbConnect() { _sqlConn = new SqlConnection() { ConnectionString = @"Server=.\SQLExpress;Database=Movies;Trusted_Connection=True;" }; _sqlConn.Open(); } static void CreateXml(DataTable dataTable) { var movieDoc = new XDocument (new XElement("Root", new XAttribute("DataType", "MovieListing"), new XElement("MovieCollection"))); foreach (DataRow dataRow in dataTable.Rows) { var movieTitle = new XElement("Id", new XAttribute("MovieId",dataRow["MovieId"]), new XElement("Title", dataRow["Title"])); if (movieDoc.Root != null) movieDoc.Root.Element("MovieCollection").Add(movieTitle); } XDocument outputDoc = XDocument.Load(movieDoc.CreateReader()); outputDoc.Save(@"movieList.xml"); } } }