class CaoZuoXml { XmlDocument xmlDoc = null; String xmlPath = ""; public CaoZuoXml(String xmlPath)//The path where the file is located (Directory.GetCurrentDirectory() + @"\data.xml") { this.xmlPath = xmlPath; xmlDoc = new XmlDocument(); xmlDoc.Load(xmlPath); } /// <summary> /// add node /// </summary> /// <param name="namestr"></param> /// <param name="urlstr"></param> public void Add(String str) { try { XmlNode root = xmlDoc.SelectSingleNode("root"); XmlElement name = xmlDoc.CreateElement("node1"); name.InnerText = str; root.AppendChild(name); xmlDoc.Save(this.xmlPath); }catch(Exception ex) { MessageBox.Show(ex.Message); } } /// <summary> /// delete node /// </summary> /// <param name="name"></param> public Boolean DeleteXml(String name)//Delete according to the incoming node content { try { XmlNode root = xmlDoc.SelectSingleNode("root"); XmlNodeList nodelist = xmlDoc.SelectNodes("//node1"); for (int i = 0; i < nodelist.Count; i++) { if (nodelist[i].InnerText.Equals(name)) { root.RemoveChild(nodelist[i]); xmlDoc.Save(this.xmlPath); return true; } } return false; } catch(Exception ex) { return false; } }
public DataTable GetXml()//Get the data table of the document { try { XmlNodeList list_name = xmlDoc.SelectNodes("//node1"); DataTable dt = new DataTable("data"); DataColumn dc = null; dc = dt.Columns.Add("col1", Type.GetType("System.String")); dc = dt.Columns.Add("col2", Type.GetType("System.String")); for (int i = 0; i < list_name.Count; i++) { DataRow newRow; newRow = dt.NewRow(); String[] text = new String[2]; newRow["col1"] = list_name[i].InnerText; newRow["col2"] = " "; dt.Rows.Add(newRow); } return dt; } catch(Exception ex) { return null; } }