将xml文件的数据载入到DataSet中,在读取出来

本文介绍了一个使用C#将SQL数据库中的数据读取并写入XML文件的例子。通过SqlConnection连接数据库,SqlDataAdapter获取数据,并用DataSet进行数据管理。然后,使用DataSet的WriteXml方法将数据写入XML文件,并通过ReadXml方法从XML文件中读取数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值