- usingSystem;
- usingSystem.Windows.Forms;
- usingSystem.Xml;
- namespaceXMLDemo
- {
- publicpartialclassFrmDOM:Form
- publicFrmDOM()
- InitializeComponent();
- }
- privatevoidbtnLoad_Click(objectsender,EventArgse)
- {
- XmlDocumentxmlDoc=newXmlDocument();
- xmlDoc.Load("Books.xml");
- MessageBox.Show(xmlDoc.InnerXml);
- }
- voidbtnCreate_Click( //xml文档
- XmlDeclarationdec=xmlDoc.CreateXmlDeclaration("1.0","utf-8",null);
- xmlDoc.AppendChild(dec);
- //创建根节点
- XmlElementroot=xmlDoc.CreateElement("Books");
- xmlDoc.AppendChild(root);
- //节点及元素
- XmlNodebook=xmlDoc.CreateElement("Book");
- XmlElementtitle=GetXmlElement(xmlDoc,"Title","WindowForm");
- XmlElementisbn=GetXmlElement(xmlDoc,"ISBN","111111");
- XmlElementauthor=GetXmlElement(xmlDoc,"Author","amandag");
- XmlElementprice=GetXmlElement(xmlDoc,"Price","128.00");
- price.SetAttribute("Unit","¥");
- book.AppendChild(title);
- book.AppendChild(isbn);
- book.AppendChild(author);
- book.AppendChild(price);
- root.AppendChild(book);
- xmlDoc.Save("Books.xml");
- MessageBox.Show("数据已写入!");
- voidbtnInsert_Click( XmlNoderoot=xmlDoc.SelectSingleNode("Books");
- XmlElementbook=xmlDoc.CreateElement("Book");
- "ASP.NET");
- "222222");
- "moon");
- "111.00");
- MessageBox.Show("数据已插入!");
- voidbtnUpdate_Click(//方法1:获取Books//Book节点的第一个子节点
- XmlNodeListnodeList=xmlDoc.SelectSingleNode("Books//Book").ChildNodes;
- XmlElementxe=null;
- //遍历所有子节点
- foreach(XmlNodexninnodeList)
- //将子节点类型转换为XmlElement类型
- xe=(XmlElement)xn;
- if(xe.Name=="Author"&&xe.InnerText=="amandag")
- xe.InnerText="高歌";
- if(xe.GetAttribute("Unit")=="¥")
- xe.SetAttribute("Unit",0); background-color:inherit">//方法2:
- XmlNodenode=xmlDoc.SelectSingleNode("Books//Book[Author=\"moon\"]//Author");
- if(node!=null)
- node.InnerText="宝贝";
- xmlDoc.Save("Books.xml");
- MessageBox.Show("数据已更新!");
- voidbtnDelete_Click( XmlDocumentxmlDoc=newXmlDocument();
- xmlDoc.Load("Books.xml");
- XmlNodeListnodeList=xmlDoc.SelectNodes("Books//Book//Price[@Unit=\"$\"]");
- XmlElementxe=(XmlElement)xn;
- xe.RemoveAttribute("Unit");
- MessageBox.Show("数据已删除!");
- privateXmlElementGetXmlElement(XmlDocumentdoc,153); background-color:inherit; font-weight:bold">stringelementName,153); background-color:inherit; font-weight:bold">stringvalue)
- XmlElementelement=doc.CreateElement(elementName);
- element.InnerText=value;
- returnelement;
- }