C#操作XML的代码

 
绑定控件的使用方法          
  DataSet ds = new DataSet();
            ds.ReadXml(@"TuFaType.xml");
            for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
            {
                this.comboBoxType.Items.Add(ds.Tables[0].Rows[j]["type"]);

            }
            Hashtable ht = new Hashtable();
            for (int i = 0; i < comboBoxType.Items.Count; i++)
            {
                if (!ht.ContainsValue(this.comboBoxType.Items.ToString()))
                {
                    ht.Add(i, this.comboBoxType.Items.ToString());
                }

            }
            this.comboBoxType.Items.Clear();
            foreach (DictionaryEntry de in ht)
            {
                this.comboBoxType.Items.Add(de.Value);
            }
            comboBoxType.SelectedIndex = 0;
使用XML记录事情与读取:
private void Form1_Load(object sender, EventArgs e)
        {
            if (!File.Exists("user.xml"))
            {
                
            }
            else
            {
                readerXml();
            }
            
        }
        private void buttonSave_Click(object sender, EventArgs e)
        {
            writeXml(this.textBoxName.Text,this.textBoxPwd.Text);
        }

        private void readerXml()
        {
          
            XmlTextReader readerXml = new XmlTextReader("user.xml");
            XmlDocument doc = new XmlDocument();
            doc.Load("user.xml");
            XmlNode root = doc.DocumentElement;
            this.textBoxName.Text=root.SelectSingleNode("userName").InnerText;
            this.textBoxPwd.Text=root.SelectSingleNode("pwd").InnerText;

            
        }

        private void writeXml(string userName,string pwd)
        {
            CreateXml();

            XmlDocument doc = new XmlDocument();
            doc.Load("user.xml");
            XmlElement root = doc.DocumentElement;

            XmlElement userNames = doc.CreateElement("userName");
            userNames.InnerText = userName;
            XmlElement pwds = doc.CreateElement("pwd");
            pwds.InnerText = pwd;

            root.AppendChild(userNames);
            root.AppendChild(pwds);
            doc.Save("user.xml");
              
        }

        private static void CreateXml()
        {
            XmlTextWriter writeXml = new XmlTextWriter("user.xml", Encoding.UTF8);
            writeXml.Formatting = Formatting.Indented;
            writeXml.Indentation = 5;
            writeXml.WriteStartDocument();

            writeXml.WriteStartElement("user");
            writeXml.Close();
        }
    }
原文地址:https://www.cnblogs.com/mingyan/p/1491293.html