将数据库里的数据导出到xml文件:
string str = ConfigurationManager.ConnectionStrings["sqlcnn"].ConnectionString;
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = "select * from book";
cmd.ExecuteScalar();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
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());
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);
}
FileStream stream = File.OpenWrite(Server.MapPath("a.xml"));
StreamWriter writer = new StreamWriter(stream);
writer.Write(xmlbookstore.ToString());
writer.Flush();
writer.Dispose();
将xml文件导入到数据库:
string str = ConfigurationManager.ConnectionStrings["sqlcnn"].ConnectionString;
Stream reader = File.OpenRead(Server.MapPath("book.xml"));
XDocument doc = XDocument.Load(reader);
foreach (XElement element in doc.Root.Descendants("book"))
{
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = 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);
int i=cmd.ExecuteNonQuery();
if (i > 0)
{
ClientScript.RegisterStartupScript(GetType(), "提示", "<script>alert('导入成功!');</script>");
}
}