using (SqlConnection sqlCnn = new SqlConnection(str))
{
using (SqlCommand sqlCmm = sqlCnn.CreateCommand())
{
sqlCmm.CommandText = "select title,year,price,author,gender,age from book";
SqlDataAdapter sda = new SqlDataAdapter(sqlCmm);
DataSet ds = new DataSet();
sda.Fill(ds);
DataTable dt = ds.Tables[0];
XElement xmlbookstore = new XElement("bookstore");
for (int i = 0; i < dt.Rows.Count; i++)
{
XElement xmlbook = new XElement("book");
XElement xmltitle = new XElement("title", dt.Rows[i]["title"].ToString());
XElement xmlauthor = new XElement("author", dt.Rows[i]["author"].ToString());
xmlauthor.SetAttributeValue("gender", dt.Rows[i]["gender"].ToString());
xmlauthor.SetAttributeValue("age", dt.Rows[i]["age"].ToString());
XElement xmlyear = new XElement("year", dt.Rows[i]["year"].ToString());
XElement xmlprice = new XElement("price", dt.Rows[i]["price"].ToString());
xmlbook.Add(xmltitle);
xmlbook.Add(xmlauthor);
xmlbook.Add(xmlyear);
xmlbook.Add(xmlprice);
xmlbookstore.Add(xmlbook);
}
//Response.Write(xmlbookstore.ToString());
FileStream Stream = File.OpenWrite(Server.MapPath("book1.xml"));
StreamWriter writer = new StreamWriter(Stream);
writer.WriteLine(xmlbookstore);
writer.Flush();
Stream.Dispose();
ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('导出成功')</script>");
}
}
}
数据库导出到xml中
最新推荐文章于 2021-11-19 15:50:24 发布