编写XML文档,并显示再页面中:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = System.Text.Encoding.UTF8; //设置文档编码方式为utf8
settings.Indent = true; //文档缩进
using (XmlWriter writer = XmlWriter.Create(this.Response.Output, settings))
{
writer.WriteStartDocument(); //开始写<?xml version="1.0" ....
writer.WriteStartElement("books"); //写入根结点
writer.WriteStartElement("book");
writer.WriteStartAttribute("id"); //写id属性
writer.WriteValue("1"); //写属性值
writer.WriteEndAttribute(); //属性结束
writer.WriteStartElement("author");
writer.WriteString("john");
writer.WriteEndElement(); //结束author元素
writer.WriteStartElement("publisher");
writer.WriteString("清华大学出版社");
writer.WriteEndElement(); //结束publisher元素
writer.WriteEndElement(); //结束book元素
writer.WriteEndElement(); //结束books元素
}
XML文档的读取(两种方法)和删除:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
public partial class Default3 : System.Web.UI.Page
{
XmlDocument xdoc;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack){
xdoc = new XmlDocument();
xdoc.Load(Server.MapPath("books.xml"));
XmlNodeList list = xdoc.GetElementsByTagName("name");
foreach (XmlNode node in list){
this.DropDownList1.Items.Add(node.InnerText);
}
Session["doc"] = xdoc; //页面第一次装载时,将xml文档放入Session
}
else{
xdoc = Session["doc"] as XmlDocument;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
XmlNode node = xdoc.DocumentElement.SelectSingleNode("book[name='" +
this.DropDownList1.Text + "']");//根据特定的Xpath表达式,在文档中查找第一个匹配的节点
#region 方法二:遍历book节点的子节点集合
foreach (XmlNode item in node.ChildNodes)
{
if (item.LocalName == "author")
this.txtAuthor.Text = item.InnerText;
if (item.LocalName == "isbn")
this.txtISBN.Text = item.InnerText;
if (item.LocalName == "publisher")
this.txtPublisher.Text = item.InnerText;
if (item.LocalName == "price")
this.txtPrice.Text = item.InnerText;
if (item.LocalName == "date")
this.txtDate.Text = item.InnerText;
}
#endregion
#region 方法一:准确查找节点
string author = node.SelectSingleNode("author").InnerText;
this.txtAuthor.Text = author;
this.txtDate.Text = node.SelectSingleNode("date").InnerText;
this.txtISBN.Text = node.SelectSingleNode("isbn").InnerText;
this.txtPrice.Text = node.SelectSingleNode("price").InnerText;
this.txtPublisher.Text = node.SelectSingleNode("publisher").InnerText;
#endregion
}
protected void Button2_Click(object sender, EventArgs e)
{
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"));
this.Response.Write("delete ok!");
}
}
}