在 .NET 環境中,把數據庫中的數據導出為 XML 是相當直接的事情。下面介紹兩種常見做法。
先連接數據庫並填充 DataSet,再調用 WriteXml 一次性導出:
1 SqlConnection conn = new SqlConnection();
2 conn.ConnectionString = "Server=127.0.0.1;User ID=sa;Password=xxx;Database=northwind;Persist Security Info=True";
3 conn.Open();
4 SqlDataAdapter da = new SqlDataAdapter("select * from 表", conn);
5 SqlCommandBuilder thisBulder = new SqlCommandBuilder(da);
6 DataSet ds = new DataSet();
7 da.Fill(ds);
8 ds.WriteXml(@"C:\temp.xml");
關鍵在於第 8 行的 ds.WriteXml,它會把整個 DataSet 的內容序列化為 XML 文件。
若希望自定義寫入方式(例如指定編碼),可以把邏輯封裝成一個方法,用 FileStream 搭配 XmlTextWriter 來輸出:
private void WriteXmlToFile(DataSet thisDataSet)
{
if (thisDataSet == null) { return; }
// Create a file name to write to.
string filename = "myXmlDoc.xml";
// Create the FileStream to write with.
System.IO.FileStream myFileStream = new System.IO.FileStream
(filename, System.IO.FileMode.Create);
// Create an XmlTextWriter with the fileStream.
System.Xml.XmlTextWriter myXmlWriter =
new System.Xml.XmlTextWriter
(myFileStream, System.Text.Encoding.Unicode);
// Write to the file with the WriteXml method.
thisDataSet.WriteXml(myXmlWriter);
myXmlWriter.Close();
}
這種寫法的好處是可以自由控制目標文件與字符編碼(此處為 Unicode),適合需要指定輸出格式的場景。兩種方法各有側重:前者簡潔快速,後者靈活可控。