//origin http://blog.csdn.net/amandag/article/details/2623322
using System;
using System.Windows.Forms;
using System.Xml;
namespace XMLDemo
{
public partial class FrmDOM : Form
{
public FrmDOM()
{
InitializeComponent();
}
private void btnLoad_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Books.xml");
MessageBox.Show(xmlDoc.InnerXml);
}
private void btnCreate_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration dec = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
xmlDoc.AppendChild(dec);
XmlElement root = xmlDoc.CreateElement("Books");
xmlDoc.AppendChild(root);
XmlNode book = xmlDoc.CreateElement("Book");
XmlElement title = GetXmlElement(xmlDoc, "Title", "Window Form");
XmlElement isbn = GetXmlElement(xmlDoc, "ISBN", "111111");
XmlElement author = GetXmlElement(xmlDoc, "Author", "amandag");
XmlElement price = 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("数据已写入!");
}
private void btnInsert_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Books.xml");
XmlNode root = xmlDoc.SelectSingleNode("Books");
XmlElement book = xmlDoc.CreateElement("Book");
XmlElement title = GetXmlElement(xmlDoc, "Title", "ASP.NET");
XmlElement isbn = GetXmlElement(xmlDoc, "ISBN", "222222");
XmlElement author = GetXmlElement(xmlDoc, "Author", "moon");
XmlElement price = GetXmlElement(xmlDoc, "Price", "111.00");
price.SetAttribute("Unit", "{1}quot;);
book.AppendChild(title);
book.AppendChild(isbn);
book.AppendChild(author);
book.AppendChild(price);
root.AppendChild(book);
xmlDoc.Save("Books.xml");
MessageBox.Show("数据已插入!");
}
private void btnUpdate_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Books.xml");
XmlNodeList nodeList = xmlDoc.SelectSingleNode("Books//Book").ChildNodes;
XmlElement xe = null;
foreach (XmlNode xn in nodeList)
{
xe = (XmlElement)xn;
if (xe.Name == "Author" && xe.InnerText == "amandag")
{
xe.InnerText = "高歌";
}
if (xe.GetAttribute("Unit") == "¥")
{
xe.SetAttribute("Unit", "{1}quot;);
}
}
XmlNode node = xmlDoc.SelectSingleNode("Books//Book[Author=\"moon\"]//Author");
if(node != null)
{
node.InnerText = "宝贝";
}
xmlDoc.Save("Books.xml");
MessageBox.Show("数据已更新!");
}
private void btnDelete_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Books.xml");
XmlNodeList nodeList = xmlDoc.SelectNodes("Books//Book//Price[@Unit=\"$\"]");
foreach (XmlNode xn in nodeList)
{
XmlElement xe = (XmlElement)xn;
xe.RemoveAttribute("Unit");
}
xmlDoc.Save("Books.xml");
MessageBox.Show("数据已删除!");
}
private XmlElement GetXmlElement(XmlDocument doc, string elementName, string value)
{
XmlElement element = doc.CreateElement(elementName);
element.InnerText = value;
return element;
}
}
}