将数据库里的数据导出到xml文件:
string str = ConfigurationManager.ConnectionStrings["sqlcnn"].ConnectionString;
SqlConnectioncon = new SqlConnection(str);
SqlCommandcmd = con.CreateCommand();
con.Open();
cmd.CommandText = "select * from book";
cmd.ExecuteScalar();
SqlDataAdapteradapter = new SqlDataAdapter(cmd);
DataTabledt = new DataTable();
adapter.Fill(dt);
XElementxmlbookstore = new XElement("bookstore");
for (int i = 0; i < dt.Rows.Count; i++)
{
XElementxmlbook = new XElement("book");
XElementxmltitle = new XElement("title", dt.Rows[i]["title"].ToString());
XElementxmlauthor = new XElement("author", dt.Rows[i]["author"].ToString());
XElementxmlyear = new XElement("year", dt.Rows[i]["year"].ToString());
XElementxmlprice = new XElement("price", dt.Rows[i]["price"].ToString());
xmlbook.Add(xmltitle);
xmlbook.Add(xmlauthor);
xmlbook.Add(xmlyear);
xmlbook.Add(xmlprice);
xmlbookstore.Add(xmlbook);
}
FileStreamstream = File.OpenWrite(Server.MapPath("a.xml"));
StreamWriterwriter = new StreamWriter(stream);
writer.Write(xmlbookstore.ToString());
writer.Flush();
writer.Dispose();
将xml文件导入到数据库:
string str = ConfigurationManager.ConnectionStrings["sqlcnn"].ConnectionString;
Streamreader = File.OpenRead(Server.MapPath("book.xml"));
XDocumentdoc = XDocument.Load(reader);
foreach(XElement element indoc.Root.Descendants("book"))
{
SqlConnectioncon = new SqlConnection(str);
SqlCommandcmd = con.CreateCommand();
con.Open();
cmd.CommandText = "insert into book(title,author, gender,age,year,price) values(@title,@author,@gender,@age,@years,@price)";
cmd.Parameters.AddWithValue("@title", element.Element("title").Value);
cmd.Parameters.AddWithValue("@author", element.Element("author").Value);
cmd.Parameters.AddWithValue("@gender", element.Element("author").Attribute("gender").Value);
cmd.Parameters.AddWithValue("@age", element.Element("author").Attribute("age").Value);
cmd.Parameters.AddWithValue("@years", element.Element("year").Value);
cmd.Parameters.AddWithValue("@price", element.Element("price").Value);
inti=cmd.ExecuteNonQuery();
if(i > 0)
{
ClientScript.RegisterStartupScript(GetType(),"提示", "<script>alert('导入成功!');</script>");
}
}