using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.sqlClient; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender,EventArgs e) { String conStr = "Data Source=localhost;Initial Catalog=db_ks;uid=sa;password=sa123"; sqlConnection myConn = new sqlConnection(conStr);//创建连接 myConn.Open();//打开连接 string cmdText = "select * from ks";//查询文本 sqlDataAdapter da = new sqlDataAdapter(cmdText,myConn);//创建数据适配器实例对象 DataSet ds = new DataSet();//创建数据集实例 da.Fill(ds,"ks");//填充 ds.WriteXml(Server.MapPath("App_Data/ks.xml"));//写入xml文件 Response.Write("已经将ks表写入到ks.xml,位于App_Data里"); } }
2.使用xmlTextWriter对象创建xml文档
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml; public partial class Default2 : System.Web.UI.Page { protected void Page_Load(object sender,EventArgs e) { XmlTextWriter xmlTW = null;//创建XmlTextWriter对象的实例 xmlTW = new XmlTextWriter(Server.MapPath("App_Data/books.xml"),null); xmlTW.Formatting = Formatting.Indented;//设置缩进格式 xmlTW.Indentation = 3; //层次,可去 xmlTW.WriteStartDocument();//文件头信息 xmlTW.WriteComment("创建日期:" + DateTime.Now);//创建注释 xmlTW.WriteStartElement("books");//根节点开始 //节点开始 xmlTW.WriteStartElement("book"); xmlTW.WriteAttributeString("Category","技术类");//属性 int intPageCount = 435; xmlTW.WriteAttributeString("PageCount",intPageCount.ToString("G")); xmlTW.WriteElementString("Title","ASP.NET动态网站开发教程");//元素 //子节点开始 xmlTW.WriteStartElement("AuthorList"); xmlTW.WriteElementString("Author","张平"); xmlTW.WriteElementString("Author","李澜"); xmlTW.WriteEndElement(); //子节点结束 xmlTW.WriteEndElement(); //结点结束 //另一个节点开始 xmlTW.WriteStartElement("book"); xmlTW.WriteAttributeString("Category","文学类");//属性 intPageCount = 500; xmlTW.WriteAttributeString("PageCount","青春赞歌");//元素 //子节点开始 xmlTW.WriteStartElement("AuthorList"); xmlTW.WriteElementString("Author","陈明"); xmlTW.WriteElementString("Author","王小虎"); xmlTW.WriteEndElement(); //子节点结束 xmlTW.WriteEndElement(); //另一结点结束 xmlTW.WriteEndElement();//根节点结束 xmlTW.Flush();//写入xml文档 xmlTW.Close();//关闭 Response.Write("xml文档已经生成"); } }原文链接:https://www.f2er.com/xml/295179.html