XML简单的增改删操作

时间:2023-03-09 20:17:54
XML简单的增改删操作

XML文件的简单增改删,每一个都可以单独拿出来使用。

新创建XML文件,<?xmlversion="1.0"encoding="utf-8"?>

<bookstore>

<bookgenre="fantasy"ISBN="2-3631-4">

<title>Oberon's Legacy</title>

<author>Corets, Eva</author>

<price>5.95</price>

</book>

</bookstore>

实现如下:

//插入节点

protected
void btn_Add_Click(object sender,
EventArgs e)

{

XmlDocument doc =
new XmlDocument();

doc.Load(@"E:\ruxiaomeng\Simple\C++\CLR\stlclr\StlClr Sample\XMLTest\bookstore.xml");

XmlNode root = doc.SelectSingleNode("bookstore");//找到根节点

XmlElement new_ele = doc.CreateElement("book");//文档创建节点<book>

new_ele.SetAttribute("genre",
"历史");

new_ele.SetAttribute("ISBN",
"100-001-*6963");//设置属性

XmlElement new_ele_childone = doc.CreateElement("title");

new_ele_childone.InnerText =
"史记"; //填充新节点内的文本。

new_ele.AppendChild(new_ele_childone);//给父节点添加子节点。

XmlElement new_ele_childtwo = doc.CreateElement("author");

new_ele_childtwo.InnerText =
"司马迁";

new_ele.AppendChild(new_ele_childtwo);

XmlElement new_ele_childthree = doc.CreateElement("price");

new_ele_childthree.InnerText =
"90.36";

new_ele.AppendChild(new_ele_childthree);

root.AppendChild(new_ele);//根节点添加新创建的子节点!

doc.Save(@"E:\ruxiaomeng\Simple\C++\CLR\stlclr\StlClr Sample\XMLTest\bookstore.xml");//记得一定要保存!

}

//更新属性和节点值

protected
void btn_Edit_Click(object sender,
EventArgs e)

{

XmlDocument doc =
new XmlDocument();

doc.Load(@"E:\ruxiaomeng\Simple\C++\CLR\stlclr\StlClr Sample\XMLTest\bookstore.xml");

XmlNodeList nodes = doc.SelectSingleNode("bookstore").ChildNodes;
//找到根节点下的所有子节点。

foreach (XmlElement item
in nodes)

{

if (item.GetAttribute("genre") ==
"历史")//找属性

{

item.SetAttribute("genre",
"中国古代史");

}

XmlNodeList childsnodes = item.ChildNodes;

foreach (XmlElement childitem
in childsnodes)

{

if (childitem.Name ==
"price") //找节点

{

childitem.InnerText =
"199";

break;

}

}

}

doc.Save(@"E:\ruxiaomeng\Simple\C++\CLR\stlclr\StlClr Sample\XMLTest\bookstore.xml");

}

//删除节点的genre属性,删除price是99的节点

protected
void btn_Del_Click(object sender,
EventArgs e)

{

XmlDocument doc =
new XmlDocument();

doc.Load(@"E:\ruxiaomeng\Simple\C++\CLR\stlclr\StlClr Sample\XMLTest\bookstore.xml");

XmlNode root = doc.SelectSingleNode("bookstore");

foreach (XmlElement item
in root.ChildNodes)

{

if (item.HasAttribute("genre"))

{

item.RemoveAttribute("genre");

}

foreach (XmlElement child_item
in item)

{

if (child_item.Name ==
"price" && child_item.InnerText ==
"99")

{

root.RemoveChild(item);

}

}

}

doc.Save(@"E:\ruxiaomeng\Simple\C++\CLR\stlclr\StlClr Sample\XMLTest\bookstore.xml");

}