将数据集导出到 XML 文件






2.35/5 (18投票s)
将数据集导出/创建为 Xml 文件。
引言
这篇文章是关于将数据集导出到 XML 文件的。这段代码片段从数据库中获取一个数据集,并在单击按钮后将其填充到 .aspx 页面上。这段代码在当前位置创建一个文件,在本例中,它将在 C:/Inetpub/wwwroot/ExportImport/… 中创建。这很有用,因为它非常容易理解和编写。
使用代码
将此代码放入你的代码隐藏文件中
首先,你需要在 WEB.CONFIG 文件中创建一个连接字符串。
// web.config setting add name="ExportImportCS" connectionString="Data Source=BROAD-12\SQLEXPRESS;Initial Catalog=LibSYSDB;Integrated Security=True" providerName="System.Data.SqlClient // C# Code using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using System.Xml.Serialization; using System.Xml; using System.IO; public partial class ExportToXml : System.Web.UI.Page { //Connection setting on .aspx page SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ExportImportCS"].ConnectionString); protected void Page_Load(object sender, EventArgs e) { } // Method created for populate the dataset and grid public void ConnectionXML() { SqlCommand command = new SqlCommand(); command.CommandText = "SELECT * FROM BookIssueDetails"; command.CommandType = CommandType.Text; command.Connection = con; SqlDataAdapter da = new SqlDataAdapter(command); DataSet ds = new DataSet(); da.Fill(ds, "BookIssueDetails"); if (ds.Tables[0].Rows.Count > 0) { grdXML.DataSource = ds; grdXML.DataBind(); } // Get a StreamWriter object StreamWriter xmlDoc = new StreamWriter(Server.MapPath("~/FileTest/Testdo.xml"), false); // Apply the WriteXml method to write an XML document ds.WriteXml(xmlDoc); xmlDoc.Close(); } //On click of button event protected void btnExportToXml_Click(object sender, EventArgs e) { ConnectionXML(); } }
Remember to set the .aspx page must download the zip file.
关注点
我希望我解释得足够清楚。如果你喜欢这段代码,请为这篇文章投票……拜托了!谢谢你
历史
我在印度的跨国公司担任软件工程师。