C# XML操作範例
travianBOT> settinginfo server="伺服器名稱" account="帳號" password="密碼" delay="20000" /> travianBOT> Xml讀取: openFileDialog1.Filter = "XML設定檔|*.xml"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { XmlDocument document = new XmlDocument(); document.Load(openFileDialog1.FileName); try { textBox_ServerName.Text = document.SelectSingleNode("/travianBOT/settinginfo").Attributes["server"].Value; textBox_Account.Text = document.SelectSingleNode("/travianBOT/settinginfo").Attributes["account"].Value; textBox_Password.Text = document.SelectSingleNode("/travianBOT/settinginfo").Attributes["password"].Value; textBox_timerInterval.Text = document.SelectSingleNode("/travianBOT/settinginfo").Attributes["delay"].Value; } catch (Exception ee) { MessageBox.Show("讀取失敗!可能是資料格式不完整~ 如果有中文資訊請確認儲存編碼為UTF8"); label_info.Text = ee.ToString(); } } Xml寫入: saveFileDialog1.Filter = "XML設定檔|*.xml"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { XmlDocument document = new XmlDocument(); document.AppendChild(document.CreateXmlDeclaration("1.0", "UTF-8", ""));//將宣告節點加入document中 XmlNode xmlnode_travianBOT = document.CreateNode(XmlNodeType.Element, "travianBOT", ""); XmlNode xmlnode_settinginfo = document.CreateNode(XmlNodeType.Element, "settinginfo", ""); XmlAttribute xmlattribute_server = document.CreateAttribute("server"); XmlAttribute xmlattribute_account = document.CreateAttribute("account"); XmlAttribute xmlattribute_password = document.CreateAttribute("password"); XmlAttribute xmlattribute_delay = document.CreateAttribute("delay"); xmlattribute_server.Value = textBox_ServerName.Text; xmlattribute_account.Value = textBox_Account.Text; xmlattribute_password.Value = textBox_Password.Text; xmlattribute_delay.Value = textBox_timerInterval.Text; xmlnode_settinginfo.Attributes.Append(xmlattribute_server);//將屬性加入xmlnode_settinginfo節點下 xmlnode_settinginfo.Attributes.Append(xmlattribute_account);//將屬性加入xmlnode_settinginfo節點下 xmlnode_settinginfo.Attributes.Append(xmlattribute_password);//將屬性加入xmlnode_settinginfo節點下 xmlnode_settinginfo.Attributes.Append(xmlattribute_delay);//將屬性加入xmlnode_settinginfo節點下 xmlnode_travianBOT.AppendChild(xmlnode_settinginfo);//將xmlnode_settinginfo節點加入xmlnode_travianBOT節點下 document.AppendChild(xmlnode_travianBOT); //將xmlnode_travianBOT節點加入document中 document.Save(saveFileDialog1.FileName); }