天天看點

sql初始化XML操作

/// <summary>

/// 添加記錄

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void button1_Click(object sender, EventArgs e)

{

try

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load("bookstore.xml"); // 載入xml檔案

XmlNode root = xmlDoc.SelectSingleNode("bookstore");// 查找<bookstore>

XmlElement xe1 = xmlDoc.CreateElement("book"); // 建立一個<book>節點

xe1.SetAttribute("genre", genre.Text); // 設定該節點genre屬性

xe1.SetAttribute("ISBN", ISBN.Text); // 設定該節點ISBN屬性

XmlElement xesub1 = xmlDoc.CreateElement("title"); // 建立一個<title>節點

xesub1.InnerText = title.Text; // 設定文本節點

xe1.AppendChild(xesub1); // 添加到<book>節點中

XmlElement xesub2 = xmlDoc.CreateElement("author"); // 建立一個<author>節點

xesub2.InnerText = author.Text; // 設定文本節點

xe1.AppendChild(xesub2); // 添加到<author>節點中

XmlElement xesub3 = xmlDoc.CreateElement("price"); // 建立一個<price>節點

xesub3.InnerText = price.Text; // 設定文本節點

xe1.AppendChild(xesub3); // 添加到<price>節點中

root.AppendChild(xe1); // 添加到<bookstore>節點中

xmlDoc.Save("bookstore.xml"); // 儲存

}

catch (XmlException Xe)

MessageBox.Show(Xe.Message);

/// 修改記錄

private void button3_Click(object sender, EventArgs e)

XmlNodeList nodeList = xmlDoc.SelectSingleNode("bookstore").ChildNodes; //擷取bookstore節點的所有子節點

foreach (XmlNode xn in nodeList) //周遊所有子節點

XmlElement xe = (XmlElement)xn; //将子節點類型轉換為XmlElement類型

if (xe.GetAttribute("genre") == "tajear") //如果genre屬性值為“李贊紅”

xe.SetAttribute("genre", "update李贊紅"); //則修改該屬性為“update李贊紅”

XmlNodeList nls = xe.ChildNodes; //繼續擷取xe子節點的所有子節點

foreach (XmlNode xn1 in nls) //周遊

XmlElement xe2 = (XmlElement)xn1; //轉換類型

if (xe2.Name == "author") //如果找到

xe2.InnerText = "亞勝"; //則修改

break; //找到退出來就可以了

break;

xmlDoc.Save("bookstore.xml");//儲存。

/// 删除記錄

private void button2_Click(object sender, EventArgs e)

XmlNodeList xnl = xmlDoc.SelectSingleNode("bookstore").ChildNodes;

foreach (XmlNode xn in xnl)

XmlElement xe = (XmlElement)xn;

if (xe.GetAttribute("genre") == "jujear")

xe.RemoveAttribute("genre");//删除genre屬性

else if (xe.GetAttribute("genre") == "update李贊紅")

xe.RemoveAll();//删除該節點的全部内容

xmlDoc.Save("bookstore.xml");

private void button4_Click(object sender, EventArgs e)

XmlNode xn = xmlDoc.SelectSingleNode("bookstore");

XmlNodeList xnl = xn.ChildNodes;

foreach (XmlNode xnf in xnl)

XmlElement xe = (XmlElement)xnf;

Console.WriteLine(xe.GetAttribute("genre"));// 顯示屬性值

Console.WriteLine(xe.GetAttribute("ISBN"));

XmlNodeList xnf1 = xe.ChildNodes;

foreach (XmlNode xn2 in xnf1)

Console.WriteLine(xn2.InnerText);// 顯示子節點點文本

本文轉自歡醉部落格園部落格,原文連結http://www.cnblogs.com/zhangs1986/p/3644066.html如需轉載請自行聯系原作者

歡醉