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();
}
}