类:
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()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
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 .txt_author .Text ,this .txt_pub .Text ,this .txt_date .Text ,this .txt_bookname .Text ,this .txt_isbn .Text ,this .txt_price .Text );
//执行添加命令
myxml.AddNode();