代码之家  ›  专栏  ›  技术社区  ›  SMUsamaShah

如何使用数据集保存到XML

  •  2
  • SMUsamaShah  · 技术社区  · 14 年前

    我使用一个SQL数据库来保存一个简单的笔记记录应用程序的数据,使用数据集和GUI与数据库绑定在一起。简单的工作。 使用SQL在这里是无用的,我想将数据保存到一个简单的XML文件,而不是使用相同数据集的SQL。

    我正在使用Visual Studio 2010并在C.NET 4.0中编程

    4 回复  |  直到 12 年前
        1
  •  3
  •   Lorenzo OnoSendai    14 年前

    将单个表的数据集转换为XML

    private void SingleTableToXml()
    {
        DataSet myDS = getDataSet();
    
        // To write out the contents of the DataSet as XML,
        // use a file name to call the WriteXml method of the DataSet class
        myDS.WriteXml(Server.MapPath("filename.xml"), XmlWriteMode.IgnoreSchema);
    }
    

    如果数据集中有多个表,比如说它是一个主-细节关系,那么方法是完全相同的。只需确保在表之间创建数据关系并设置关系 Nested 属性设置为true,如下代码所示

    //Get the primary key column from the master table
    DataColumn primarykey = myDS.Tables["Categories"].Columns["CategoryID"];
    //Get the foreign key column from the detail table
    DataColumn foreignkey = myDS.Tables["Products"].Columns["CategoryID"];
    
    //Assign a relation
    DataRelation relation = myDS.Relations.Add(primarykey, foreignkey);
    
    //Ask ADO.NET to generate nested XML nodes
    relation.Nested = true;
    

    希望它有帮助

        2
  •  2
  •   Baked Potato    13 年前

    我用的是:

            private void buttonSaveXML_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFile = new SaveFileDialog();
            saveFile.Filter = "XML Files|*.xml";
            saveFile.Title = "Save a Xml File";
            saveFile.ShowDialog();
            if (saveFile.FileName != "")
            {
                FileStream fs =
                    (FileStream)saveFile.OpenFile();
                DataSet.WriteXml(fs);
            }
        {
    

    数据集是我使用的数据集,最好制作一个单独的按钮以便使用。

        3
  •  1
  •   David    14 年前

    您没有指定编程环境。假设您正在使用.NET…

    使用 WriteXml 数据集的方法。

    这里有一篇文章: http://msdn.microsoft.com/en-us/library/ms233698%28VS.80%29.aspx

        4
  •  1
  •   BoltClock    12 年前

    下面是从数据集生成XML的好例子

       DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        DataColumn dc;
        DataRow dr;
        ds.DataSetName = "products";
        dt.TableName = "product";
    
        dc = new DataColumn("product_id");
        dt.Columns.Add(dc);
    
        dc = new DataColumn("product_name");
        dt.Columns.Add(dc);
    
        dr = dt.NewRow();
        dr["product_id"] = 1;
        dr["product_name"] = "Monitor";
        dt.Rows.Add(dr);
    
        dr = dt.NewRow();
        dr["product_id"] = 2;
        dr["product_name"] = "Mouse";
        dt.Rows.Add(dr);
    
        dr = dt.NewRow();
        dr["product_id"] = 3;
        dr["product_name"] = "KeyBoard";
        dt.Rows.Add(dr);
    
        ds.Tables.Add(dt);
        string strXML= ds.GetXml();
    
        System.IO.StreamWriter sw = new System.IO.StreamWriter(Server.MapPath("datasetxml.xml"));
        sw.WriteLine(strXML);
        sw.Close();