public partial class XMLDemo : System.Web.UI.Page
{
private SqlConnection conn;
private SqlDataAdapter dad;
private DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
this.conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["pubsConnectionString"].ToString());
this.dad = new SqlDataAdapter("select job_id,job_desc from jobs ", conn);
this.ds = new DataSet();
this.dad.Fill(ds);
// Set the file path and name. Modify this for your purposes.
string filename = this.Server.MapPath("wr.xml");
//// Create a FileStream object with the file path and name.
//System.IO.FileStream stream = new System.IO.FileStream
// (filename, System.IO.FileMode.Create);
//// Create a new XmlTextWriter object with the FileStream.
//System.Xml.XmlTextWriter writer =
// new System.Xml.XmlTextWriter(stream,
// System.Text.Encoding.Unicode);
//若要将数据写入 XML 文档,请使用 WriteXml 方法。
ds.DataSetName = "jobs";//设置当前DataSet的名称,做xml文档的根元素
ds.Tables[0].TableName = "job";//设置当前DataSet下的DataTable的名称,做xml文档的子元素
ds.WriteXml(filename); //写入xml文件
// Write the schema into the DataSet and close the reader.
//this.ds.WriteXmlSchema(filename);
/*使用 WriteXmlSchema 方法将 DataSet 的架构写入 XML 文档。架构包括表、关系和约束定义。
* 若要将架构写入 XML 文档,请使用 WriteXmlSchema 方法。使用 XSD 标准编写 XML 架构。
从 System.Xml.XmlWriter 类继承的一个类是 System.Xml.XmlTextWriter 类。*/
//writer.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
/*ReadXml 方法提供了只将数据或同时将数据和架构从 XML 文档读入 DataSet 的方式,
* 而 ReadXmlSchema 方法仅读架构。若要同时读数据和架构,请使用包括 mode 参数
* 的 ReadXML 重载之一,并将其值设置为 ReadSchema。*/
DataSet ds = new DataSet();//创建一个新的DataSet,
//将读出来的数据放人ds;且绑定到DataGrid控件中。
ds.ReadXml(this.Server.MapPath("wr.xml"));
this.DataGrid1.DataSource = ds.Tables[0];
this.DataGrid1.DataBind();
}
}