通过DataSet 来读写XML

来源:互联网 发布:手机淘宝宝贝排名查询 编辑:程序博客网 时间:2024/04/27 00:56

通过DataSet 来读写XML的相关代码,整理了一下。

内容比较简单,也最基础。 mark一下,以后查阅用。


using System;using System.Collections.Generic;using System.Text;using System.Data;using System.IO;using System.Xml;using System.Xml.XPath;namespace WindowsApplication2{    class XmlReader    {        private string _filePath = @"C:\Test.xml";        // 读取XML        public void ReadXmlFile()        {            if (File.Exists(_filePath))            {                DataSet ds = new DataSet();                ds.ReadXml(_filePath);                if (ds.Tables["MyTable"] != null)                {                    DataTable dt = ds.Tables["MyTable"];                    for (int i = 0; i < dt.Rows.Count; i++)                    {                        string str1 = dt.Rows[i]["Data1"].ToString(); //取得结点1的值                        string str2 = dt.Rows[i]["Data2"].ToString(); //取得结点2的值                    }                }            }        }        // 写入XML        public void WriteXmlFile()        {            XmlTextWriter wr = null;            try            {                DataSet ds = new DataSet("MyData");                DataTable tb = new DataTable("MyTable");                tb.Columns.Add("Data1", typeof(int));                tb.Columns.Add("Data2", typeof(string));                for (int i = 0; i < 5; i++)                {                    DataRow r = tb.NewRow();                    r["Data1"] = i;                    r["Data2"] = i.ToString();                    tb.Rows.Add(r);                }                ds.Tables.Add(tb);                wr = new XmlTextWriter(_filePath, System.Text.Encoding.UTF8);                wr.Formatting = Formatting.Indented;                wr.WriteStartDocument();                ds.WriteXml(wr);                wr.WriteEndDocument();            }            finally            {                if (wr != null)                {                    wr.Close();                }            }        }    }}



原创粉丝点击