以知已XML文件:
<? xml version=”1.0” encoding=”gb2312” ?>
<bookstore>
<book genre=”fantasy” ISBN=”2-3631-4”>
<titel>Oberon’s Legacy</titel>
<author>123456789</author>
<price>12.3</price>
</book>
</bookstore>
1. 往<bookstroe>节点中插入一个<book>节点
XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load(“bookstore.xml”);//也可以用@”具体的路径”,如@”C:/bookstore.xml”
XmlNode root=xmlDoc.SelectSingleNode(“bookstore”);//查找<bookstore>
XmlElement xe1=xmlDoc.CreateElement(“book”);//创建一个<book>节点
Xe1.SetAttribute(“genre”,”wzk”);//设置该节点genre属性
Xe1.SetAttribute(“ISBN”,”2-3631-4”);//设置改节点ISBN属性
XmlElement xe2=xmlDoc.CreateElement(“title”);
Xe2.InnerText=”xml文件操作”;
Xe1.AppendChild(xe2);//添加到<book>节点中
xmlElement xe3=xmlDoc.CreateElement(“author”);
xe3.InnerText=”houj”;
xe1.AppendChild(xe3);
xmlElement xe4=xmlDoc.CreateElement(“price”);
xe4.InnerText=”15.3”;
xe1.AppendChild(ex4);
root.AppendChild(xe1);//添加到<bookstore>节点中
xmlDoc.Save(“bookstore.xml”);
2. 修改节点:将genre属性值为 houj 的节点的的genre值改为 updatahouj,将该节点的子节点<author>的文件修改为 hjm
xmlNodeList nodeList=xmlDoc.SelectSingleNode(“bookstore”).ChildNodes;//获取bookstore节点下的所有子节点
foreach(XmlNode xn in nodeList)
{
XmlElement xe=(XmlElement)xn;//将子节点转化为XmlElement;
If(xe.GetAttribute(“genre”)==”houj”)
{
Xe.SetAttribute(“genre”,”updatehouj”);
XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点。
foreach(XmlNode xn1 in nls)
{
xmlElement xe2=(xmlElement)xn1;
if(xe2.Name==”author”)
{
Xe2.InnerText=”hjm”;
Break;
}
}
Break;
}
}
xmlDoc.Save(“bookstore.xml”);
3. 删除<book genre=”fantasy” ISBN=”2-3631-4”>节点的genre属性,删除<book genre=”updatehouj” ISBN=”2-3631-4” >节点
XmlNodeList xnl=xmlDoc.SelectSingleNode(“bookstore”).ChildNodes;
Foreach(XmlNode xn in xnl)
{
XmlElement xe=(xmlElement)xn;
If(xe.GetAttribure(“genre”)==”fantasy”)
{
Xe.RemoveAttribure(“genre”);//删除genre属性
}
Else if(xe.GetAttribure(“genre”==”updatehouj”))
{
Xe.RemoveAll();//删除该节点的全部内容
}
}
XmlDoc.Save(“bookstore.xml”);
4. 显示所有数据
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);
}
}