Export SQL Server Database Table to XML Using Linq

2019-05-10 11:01发布

问题:

I know how to do simple Linq To XML. Export a sql server database table data. A simple query like follow will work:

xmlDoc = new XElement("TestPoints",
                from test in myDB.TestPoints
                select
                new XElement("TestPoint",
                    new XElement("Id", test.Id),
                    new XElement("Value", test.Value),
                    new XElement("Time", test.Time),
                    new XElement("TestId", test.TestId)
                    )
                );
            xmlDoc.Save("test.xml");

However, in this case, i need to specify every database column those I need to export. What I need is to export a table which have more than 30 columns. Now, its a bit painful to make such repetitively task of creating new XElement. Is there any way to dump the full table and all its columns/rows to a xml file in LinQ easily please? Without specify each column externally. Thanks.

回答1:

Put Data of sql server table in DataTable

and than use DataTable.WriteXml will do your task easily.