您的位置:首页 > 其它

xml节点 增删改

2011-12-01 20:44 155 查看
首先写个类:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Xml;

/// <summary>

///Class1 的摘要说明

/// </summary>

public class Class1

{

private XmlDocument xmlDoc;

private string author;

private string publisher;

private string date;

private string name;

private string isbn;

private string price;

public Class1(string au, string pu, string date, string na, string isbn, string price)

{

this.author = au;

this.publisher = pu;

this.date = date;

this.name = na;

this.isbn = isbn;

this.price = price;

}

/// <summary>

/// 加载XML文件的方法

/// </summary>

/// <param name="xmlfile">XML文件路径</param>

private void LoadXml()

{

xmlDoc = new XmlDocument();

xmlDoc.Load(System.Web.HttpContext.Current.Server.MapPath("books.xml"));

}

public void AddNode()

{

//加载文档

LoadXml();

//选择根节点

XmlNode xmldocboot = xmlDoc.SelectSingleNode("books");

//开始添加节点及节点的属性

XmlElement ele = xmlDoc.CreateElement("book");

XmlElement ele1 = xmlDoc.CreateElement("author");

ele1.InnerText = author;

XmlElement ele2 = xmlDoc.CreateElement("publisher");

ele2.InnerText = publisher;

XmlElement ele3 = xmlDoc.CreateElement("date");

ele3.InnerText = date;

XmlElement ele4 = xmlDoc.CreateElement("name");

ele4.InnerText = name;

XmlElement ele5 = xmlDoc.CreateElement("isbn");

ele5.InnerText = isbn;

XmlElement ele6 = xmlDoc.CreateElement("price");

ele6.InnerText = price;

ele.AppendChild(ele1);

ele.AppendChild(ele2);

ele.AppendChild(ele3);

ele.AppendChild(ele4);

ele.AppendChild(ele5);

ele.AppendChild(ele6);

//将节点保存到根节点下

xmldocboot.AppendChild(ele);

//保存XML文件的修改-此处要注意

xmlDoc.Save(System.Web.HttpContext.Current.Server.MapPath("books.xml"));

}

}

添加节点:

Class1 myxml = new Class1(this.TextBox1.Text, this.TextBox4.Text, this.TextBox5.Text, this.TextBox6.Text, this.TextBox2.Text, this.TextBox3.Text);

//执行添加命令

myxml.AddNode();

更改节点:

XmlNode node = xdoc.DocumentElement.SelectSingleNode("book[name='" + this.DropDownList1.Text + "']");

XmlElement elem = (XmlElement)node.SelectSingleNode("author");

elem.InnerText = this.TextBox1.Text;

elem = (XmlElement)node.SelectSingleNode("publisher");

elem.InnerText = this.TextBox4.Text;

elem = (XmlElement)node.SelectSingleNode("date");

elem.InnerText = this.TextBox5.Text;

elem = (XmlElement)node.SelectSingleNode("price");

elem.InnerText = this.TextBox3.Text;

elem = (XmlElement)node.SelectSingleNode("isbn");

elem.InnerText = this.TextBox2.Text;

xdoc.Save(Server.MapPath("books.xml"));

this.Response.Write("修改成功!");

删除节点:

XmlNode node = xdoc.DocumentElement.SelectSingleNode("book[name='" + this.DropDownList1.Text + "']");

if (node != null)

{

xdoc.DocumentElement.RemoveChild(node);

this.DropDownList1.Items.RemoveAt(this.DropDownList1.SelectedIndex);

xdoc.Save(Server.MapPath("books_new.xml"));

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: