/// <summary>
/// XML文件中插入一个节点
/// </summary>
private void btnAddNode1_Click(object sender, EventArgs e)
{
// 加载Test文档
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"E:\XiaoJun\XiaoJun-Test\XML_Test_Read_Write\Test.xml");
// 查找根节点
XmlNode root = xmlDoc.SelectSingleNode("bookstore");
// 创建一个book节点
XmlElement bookNode = xmlDoc.CreateElement("book");
// 设置book节点的属性
bookNode.SetAttribute("genre", "Math");
bookNode.SetAttribute("ISBN", "000096");
root.AppendChild(bookNode);
// 设置book节点的子节点及子节点的内容
XmlElement title = xmlDoc.CreateElement("title");
title.InnerText = "C# 锐利体验";
bookNode.AppendChild(title);
XmlElement author = xmlDoc.CreateElement("author");
author.InnerText = "Xiao Jun";
bookNode.AppendChild(author);
XmlElement price = xmlDoc.CreateElement("price");
price.InnerText = "88.00";
bookNode.AppendChild(price);
// 将修改后的文档存盘
xmlDoc.Save(@"E:\XiaoJun\XiaoJun-Test\XML_Test_Read_Write\Test.xml");
}
/// <summary>
/// 显示XML文档的描述内容
/// </summary>
private void LoadMyXMLDoc(object sender, EventArgs e)
{
// 清空LisView
lboxShow.Items.Clear();
// 获取XML文档根节点
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"E:\XiaoJun\XiaoJun-Test\XML_Test_Read_Write\Test.xml");
XmlNode rootNode = xmlDoc.DocumentElement;
// 遍历取值
foreach (XmlNode node in rootNode.ChildNodes)
{
lboxShow.Items.Add(node.Name + ":");
// 取属性名值对
if (node.Attributes.Count > 0)
{
string sTemp = "";
for (int i = 0; i < node.Attributes.Count; i++)
{
sTemp += node.Attributes[i].Name + "=" + node.Attributes[i].Value + " ";
}
lboxShow.Items.Add(sTemp);
}
// 取子节点名和内容
if (node.HasChildNodes)
{
foreach (XmlNode subNode in node.ChildNodes)
{
lboxShow.Items.Add(subNode.Name + "=" + subNode.InnerXml);
}
}
// 华丽的分割线
lboxShow.Items.Add("--------------------------------------");
}
}