当前位置:编程学习 > C#/ASP.NET >>

asp.net 把数据保存到xml 与txt文件的方法

 XML是一种数据描述语言,结构比较简单,不是专业人员也可以看得懂语言所描述的内容。XML 代表Extensible Markup Language(eXtensible Markup Language的缩写,意为可扩展的标记语言)。XML是一套定义语义标记的规则,这些标记将文档分成许多部件并对这些部件加以标识。它也是元标记语言,即定义了用于定义其他与特定领域有关的、语义的、结构化的标记语言的句法语言。

保存XML数据的方法:
  在ASP.NET 2.0中,使用“XmlDocument”类实现XML数据的操作,要实现文章开头所描述的目的。实现方法的步骤如下:

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>

<script language="VB" runat="server">

  Sub Page_Load(Sender As Object, E As EventArgs)

    Dim strConnection As String
    Dim strSQL        As String
    Dim objDataSet    As New DataSet()
    Dim objConnection As OleDbConnection
    Dim objAdapter    As OleDbDataAdapter

    ' set the connection and query details
    strConnection = "Provider=Microsoft.Jet.OLEDB.4.0; " & _
                    "Data Source=" & Server.MapPath("Northwind.mdb")
    strSQL = "SELECT FirstName, LastName FROM Employees;"

    ' open the connection and set the command
    objConnection = New OledbConnection(strConnection)
    objAdapter = New OledbDataAdapter(strSQL, objConnection)

    ' fill the dataset with the data
    objAdapter.Fill(objDataSet, "Employees")

    objDataSet.WriteXml(Server.MapPath("Employees.xml"))
   
    Response.Write("<a href='Employees.xml'>View XML file</a>")

  End Sub

</script>


本文示例一下在ASP.NET把datagridview数据保存到txt文档的方法

using System.IO
public void SaveFile()
        {
            //实例化一个保存文件对话框
            SaveFileDialog sf = new SaveFileDialog();
            //设置文件保存类型
            sf.Filter = "txt文件|*.txt";
            //如果用户没有输入扩展名,自动追加后缀
            sf.AddExtension = true;
            //设置标题
            sf.Title = "写文件";
            //如果用户点击了保存按钮
            if (sf.ShowDialog() == DialogResult.OK)
            {
                //实例化一个文件流--->与写入文件相关联
                FileStream fs = new FileStream(sf.FileName, FileMode.Create);
                //实例化一个StreamWriter-->与fs相关联
                StreamWriter sw = new StreamWriter(fs);
                //开始写入
                if (this.dataGridView1.Rows.Count < 1)
                {
                    MessageBox.Show("没有数据!导出失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
                else
                {
                    for (int i = 0; i < this.dataGridView1.Rows.Count - 1; i  )
                    {
                        sw.WriteLine(this.dataGridView1.Rows[i].Cells[0].Value.ToString());
                    }
                    //sw.Write(this.textBox1.Text);
                    //清空缓冲区
                    sw.Flush();
                    //关闭流
                    sw.Close();
                    fs.Close();
                    MessageBox.Show("保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

补充:asp.net教程,XML应用 
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,