xml檔案<?xml version="1.0" encoding="utf-8"?><Books><Book ID="1"><Title>C#入門經典</Title><Price>95.00</Price></Book><Book ID="13"><Title>C#從入門到精通</Title><Price>145.00</Price></Book><Book ID="4"><Title>Java進階編程</Title><Price>165.00</Price></Book></Books> //添加xml節點 private void addxml() { XmlDocument xmldoc = new XmlDocument(); //載入xml檔案 xmldoc.Load(@"E:\Test\Test\tt.xml"); //尋找 根節點 Books XmlNode root = xmldoc.SelectSingleNode("Books"); //建立 子節點 Book XmlElement book = xmldoc.CreateElement("Book"); book.SetAttribute("ID", "2");//設定子節點屬性 //建立 Book 子節點 Title XmlElement title = xmldoc.CreateElement("Title"); title.InnerText = "C#進階編程"; //title 節點 添加到 root book.AppendChild(title); //建立 Book 子節點 Price XmlElement price = xmldoc.CreateElement("Price"); price.InnerText = "145.00"; //price 節點 添加到 root book.AppendChild(price); //最後把book 節點添加到root root.AppendChild(book); //儲存 xmldoc.Save(@"E:\Test\Test\tt.xml"); } //刪除xml 節點 private void deletexml() { XmlDocument xmldoc = new XmlDocument(); //載入xml檔案 xmldoc.Load(@"E:\Test\Test\tt.xml"); /* //尋找到ID=2的節點,刪除book 下面的子節點,最後會留下一個空的<book></book> XmlNodeList nodelist = xmldoc.SelectNodes("//Books/Book[@ID=2]");//需瞭解xpath foreach (XmlNode n in nodelist) { XmlElement xe = (XmlElement)n; //刪除屬性 xe.RemoveAllAttributes(); //刪除節點 xe.RemoveAll(); } */ //刪除 book=2 節點(包括book 節點) XmlNodeList nodelist = xmldoc.SelectNodes("//Books/Book[@ID=2]");//需瞭解xpath foreach (XmlNode n in nodelist) { n.ParentNode.RemoveChild(n); } //儲存 xmldoc.Save(@"E:\Test\Test\tt.xml"); } //修改xml 節點 private void updatexml() { XmlDocument xmldoc = new XmlDocument(); //載入xml檔案 xmldoc.Load(@"E:\Test\Test\tt.xml"); //尋找到ID=2的節點,刪除book 下面的子節點,最後會留下一個空的<book></book> XmlNodeList nodelist = xmldoc.SelectNodes("//Books/Book[@ID=3]");//需瞭解xpath foreach (XmlNode n in nodelist) { XmlElement xe = (XmlElement)n;//XmlElement繼承XmlNode //將屬性 修改為13 xe.SetAttribute("ID","13"); //尋找title節點 XmlNode nn = n.SelectSingleNode("Title"); nn.InnerText = "C#從入門到精通"; } //儲存 xmldoc.Save(@"E:\Test\Test\tt.xml"); }動作節點還有CDATA需要操作的XML檔案:<Info><Link><![CDATA[<a href="http://www.52taiqiu.com">52撞球網</a>]]></Link></Info>修改Link中的值XmlDocument xmldoc = new XmlDocument();//載入xml檔案xmldoc.Load(@"E:\Test\Test\測試.xml");XmlNode nameNode = xmldoc.SelectSingleNode("/Info/Link");nameNode.InnerText = "";//如果是修改,需要把原先的值清空。nameNode.AppendChild(xmldoc.CreateCDataSection("<a href=\"http://www.52taiqiu.com\">52撞球網</a>"));xmldoc.Save(@"E:\Test\Test\測試.xml");